问题描述
我一直在使用硒制作WhatsApp机器人,但是每次运行代码时,我都必须重新扫描Qr代码才能输入。我在youtube视频中发现此解决方案可以使用选项,但它不起作用,并返回错误selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: user data directory is already in use,please specify a unique value for --user-data-dir argument,or don't use --user-data-dir
这是我的代码
from selenium import webdriver
import time
if __name__ == '__main__':
options = webdriver.ChromeOptions()
options.add_argument(r'--user-data-dir=C:\Users\Hill\AppData\Local\Google\Chrome\User Data\Default')
options.add_argument(r'--profile-directory=Default')
driver = webdriver.Chrome(executable_path=r'C:\Program Files (x86)\chromedriver.exe',chrome_options=options)
driver.get('https://web.whatsapp.com')
time.sleep(15)
解决方法
您基本上是给Chrome浏览器两个配置文件。第一个是您的个人资料,第二个是默认个人资料。以下步骤对我有用: 手动打开Chrome,然后转到https://web.whatsapp.com,然后扫描QR码。关闭所有内容并实现以下代码(请删除实现中的注释,因为它们的语法会引起问题;-)):
options = webdriver.ChromeOptions()
options.add_argument(r'--user-data-dir=C:\Users\Hill\AppData\Local\Google\Chrome\User Data\') #here is no <Default>!!
driver = webdriver.Chrome(executable_path=r'C:\Program Files (x86)\chromedriver.exe',options=options) #selenium 4 preferes "options" -> your code is more up to date :-)
driver.get('https://web.whatsapp.com')
time.sleep(15)