在WhatsApp Web中,如果您进行检查,可以看到联系人姓名驻留在类名为'.chat'的div中。
您可以通过执行以下脚本来向WhatsApp Web中的左侧联系人添加监听器,该脚本应该在您的
whatsapp_login函数中执行。以下是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)
以下是使用
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
});
});
在您的更改活动聊天功能中,您可以执行以下操作来更改活动聊天。在这里,您将通过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()
head.click()会更改当前活跃的聊天。