繁体   English   中英

如何使用带有 selenium 的 open chromedriver

[英]how to use open chromedriver with selenium

我有代码 Python 在 WhatsApp 中使用 bot
此代码在首次运行后打开 Chrome 浏览器
我应该怎么做才能将新消息发送到之前打开的浏览器选项卡?\

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options


# SPECIFY PATH FOR CHROME DRIVER HERE
driverPath = 'E:\\PYTHON\\chromedriver.exe'
# SPECIFY PATH FOR USER DIRECTORY (just change "TEST" to your WIN10 username)
userPath = "--user-data-dir=E:\\Users\\ipm\\AppData\\Local\\Google\\Chrome\\User Data"
# SPECIFY MESSAGES HERE
messages = ["Testmessage 1", "Testmessage 2"]


# bypass QR code login after first login
options = Options()
options.add_argument(userPath)
options.add_experimental_option('useAutomationExtension', False)
options.add_experimental_option("excludeSwitches", ["enable-automation"])
driver = webdriver.Chrome(driverPath, options=options)

# open specified whatsapp chat
driver.maximize_window()
driver.get('https://web.whatsapp.com')
# time.sleep(10)
# driver.find_element_by_xpath("//*[@title='INSERT NAME OF CHAT HERE']").click()
name = input('enter name : ')
driver.find_element_by_xpath(f"//*[@title ='{name}']").click()


# Send message
driver.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div/div/div[2]/div[1]/div/div[2]').send_keys(messages[0])
driver.find_element_by_xpath('//*[@id="main"]/footer/div[1]/div/div/div[2]/div[2]/button').click()
 

我的问题是这段代码执行了一次,消息发送正确,但是如何使用之前打开的浏览器发送下一条消息呢?

这个问题有点不清楚,但按照我的理解,您可以继续使用相同的driver变量来发送下一条消息。 只要您不使用新的 webdriver 实例覆盖驱动程序变量,就可以继续在该命名空间中使用该驱动程序变量来操作该 window。

如果您使用的是 Jupyter 笔记本,则只需确保不要重新运行正在实例化驱动程序的单元格。 在其他单元格中,您可以使用driver.get()driver.find_element_...() ,这些将继续应用于现有的 window。

如果你有多个消息,你甚至可以使用 for 循环,如果合适的话:

driver.get('https://web.whatsapp.com')
name = input('enter name: ')
driver.find_element_by_xpath(f"//*[@title ='{name}']").click()


# Send messages
textbox_xpath = '//*[@id="main"]/footer/div[1]/div/div/div[2]/div[1]/div/div[2]'
send_xpath = '//*[@id="main"]/footer/div[1]/div/div/div[2]/div[2]/button'
for message in message:
    driver.find_element_by_xpath(textbox_xpath).send_keys(message)
    driver.find_element_by_xpath(send_xpath).click()

但是,如果您希望构建一个响应式机器人来侦听消息然后回复,那么 Selenium 不是实现此目的的方法。 您将需要使用 Whatsapp API。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM