首页 > 解决方案 > 为什么我不能让 Selenium 使用 Python 3.8 和 Chrome 在我的 WhatsApp Web 中写消息?

问题描述

所以我使用这个脚本:

from selenium import webdriver 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC 
from selenium.webdriver.common.keys import Keys 
from selenium.webdriver.common.by import By 
import time 

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--no-sandbox')
driver = webdriver.Chrome('C:/Users/N-Thalpy/Documents/NT/py/chromedriver.exe', chrome_options=chrome_options) 

driver.get("https://web.whatsapp.com/") 
wait = WebDriverWait(driver, 600) 


target = '"Batman"'

string = "Python 3.8"

x_arg = '//span[contains(@title,' + target + ')]'
group_title = wait.until(EC.presence_of_element_located(( 
    By.XPATH, x_arg))) 
group_title.click() 
inp_xpath = '//div[@class="_3u328"][@dir="ltr"][@data-tab="1"]'
input_box = wait.until(EC.presence_of_element_located(( 
    By.XPATH, inp_xpath))) 
for i in range(100): 
    input_box.send_keys(string + Keys.ENTER) 
    time.sleep(1) 

Chrome 会按预期在 web.whatsapp.com 中打开 - 然后它会打开“蝙蝠侠”聊天。但是,它什么也没写。我检查了属性,甚至试图更具体地了解它们,但似乎没有任何效果。我在没有沙箱选项的情况下尝试了它,但仍然没有。

编辑:我从 py.exe 控制台得到的唯一消息是:

“[13920:4684:0130/154024.795:ERROR:wmi_refresher.cc(129)] 无法添加 Win32_PerfRawData_PerfDisk_PhysicalDisk 枚举。”

标签: pythonseleniumselenium-webdriverwhatsapp

解决方案


我设法通过以下方式解决它:

  • 下载正确的 chromedriver 版本,因为我正在使用 Chrome 79 并使用 Chrome 80 的驱动程序。
  • 搜索 div 的所有属性,包括拼写检查、contenteditable 和 dir(我不知道这实际上有多相关,但以防万一)。

推荐阅读