如何使用Python 3通过selenium或javascript更改web whatsapp中的活动聊天

Kev*_*n91 7 javascript python selenium whatsapp

我通过Python通过selenium引导web whatsapp,我想知道是否可以更改活动(顶级聊天.如果收到消息,聊天将不会被设置为活动,它将始终保留在后台.

在Javascript中,可以通过以下方式查看控制台中所有聊天的列表:

Store.chat.models
Run Code Online (Sandbox Code Playgroud)

活动聊天存储在零位置,但是通过另一次聊天覆盖位置零将不会使聊天处于活动状态.

我发现有一个名为" x_active" 的变量,如果点击聊天并查看为true(其他所有人都将其视为假),则会更改.

例如:

Store.Chat.models[0].__x_active
Run Code Online (Sandbox Code Playgroud)

但是,在Chrome控制台选项卡中设置变量或true或false并未更改UI中的任何内容,因此如何实现此类行为?

Jah*_*lam 3

在 Whatsapp Web 中,如果您检查,您可以看到联系人姓名位于类“.chat”的 div 中。

您可以通过在Whatsapp_login函数中执行以下脚本来向 Whatsapp Web 左侧的联系人添加侦听器。以下是whatsapp_login函数:

def whatsapp-login(request):
    global driver

    profile = webdriver.FirefoxProfile()
    profile.accept_untrusted_certs = True
    driver = webdriver.Firefox(firefox_profile=profile)

    driver.get('https://web.whatsapp.com/')

    script_path = os.path.dirname(os.path.abspath(__file__))
    script = open(os.path.join(script_path, "add_eventlistener.js"), "r").read()

    driver.execute_script(script)
Run Code Online (Sandbox Code Playgroud)

以下是使用MutationObserver 的add_listener 脚本:

var observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                if(mutation.attributeName === 'class') {

                    var attributeValue = $(mutation.target).prop(mutation.attributeName);
                    console.log("attributeValue: "+attributeValue);
                    if(attributeValue.indexOf('hover') > -1) {

                        var user = $(mutation.target).find('.chat-title').find('span').attr('title');
                        console.log('Class attribute changed to:', attributeValue);

                        $.ajax({
                            url: 'url of change active chat function',
                            type: "POST",
                            data: {"user": user},
                            headers: {"Access-Control-Allow-Origin": "*"},
                            success: function(data) {
                                console.log(data);
                            },
                            error: function(data) {
                                console.log(data);
                            }
                        });
                    }
                }
            });
        });

        Array.prototype.forEach.call(document.querySelectorAll('.chat'), function(element, index) {
            console.log(element);
            observer.observe(element, {
                attributes: true
            });
        });
Run Code Online (Sandbox Code Playgroud)

在更改活动聊天功能中,您可以执行以下操作来更改活动聊天。在这里,您将从 ajax 调用中获取用户并遍历联系人列表:

def change_active_chat(user):
    recentList = driver.find_elements_by_xpath("//span[@class='emojitext ellipsify']")
        for head in recentList:
            if head.text == user:
                head.click()
Run Code Online (Sandbox Code Playgroud)

head.click()将更改活动聊天。