python - 使用 selenium:如何在 whatsapp 中关闭 Python 中的驱动程序后保持登录状态
问题描述
我不想一遍又一遍地登录https://web.whatsapp.com。我尝试了一些解决方案,但使用 selenium chrome 驱动程序无法正常工作。
options=Options
options.add_argument("user-data-dir=C:\\Users\\oyo\AppData\\Local\\Google\\Chrome\\User Data")
browser = webdriver.Chrome("chrome_options=options")
TypeError: add_argument() missing 1 required positional argument: 'argument'
解决方案
我可以通过向 chrome 添加 start-option 来保存会话 -> 您需要添加 option --user-data-dir <folder>
。
我使用了这些地方的代码。
- Java 或 C# 中的会话示例 - https://stackoverflow.com/a/50637211/406423
- 带有 Selenium 的 Python 中的 Whatsapp - https://www.geeksforgeeks.org/whatsapp-using-python/
我在 Ubuntu 18.04 下运行此代码。
在运行此代码之前关闭google-chrome。否则 selenium 将重新使用当前浏览器实例,并且无法使用--user-data-dir <folder>
-option 运行它。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
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
# Replace below path with the absolute path
# to chromedriver in your computer
options = webdriver.ChromeOptions();
options.add_argument("user-data-dir=~/.chrome_driver_session")
# Create the folder. Change path accordingly
driver = webdriver.Chrome('./chromedriver_78/chromedriver', chrome_options=options)
driver.get("https://web.whatsapp.com/")
wait = WebDriverWait(driver, 600)
# Replace 'Friend Name' with the name of your friend or the name of a group
target = '"Friend Name"'
# Replace the below string with your own message
# I'm unsure why it needs two empty spaces in front of it.
string = " " + "Nachricht von Wichtel_Whatsapp"
x_arg = '//span[contains(@title,' + target + ')]'
group_title = wait.until(EC.presence_of_element_located((By.XPATH, x_arg)))
group_title.click()
print("Clicked")
default_input = "Schreib eine Nachricht"
# Change the Text with the default of the input-field
inp_xpath = "//div[contains(.,'" + default_input + "')]"
input_box = wait.until(EC.presence_of_element_located((By.XPATH, inp_xpath))).find_element_by_xpath('..')
input_box.send_keys(string)
# If the Text is written in the input field, use this line:
# input_box.send_keys(string + Keys.ENTER)
推荐阅读
- sql-server - 选择描述字段而不将其包含在 GROUP BY 子句中时 GROUP BY id 的最佳方法
- google-cloud-platform - 试图反转我的 gcloud 查询返回的值序列
- python - 在 lambda 函数中使用最后一次成功的执行时间
- sql - 回滚 SQL 事务而不返回错误
- excel - 将 FSO 设置为 FileSystemObject 与 Scripting.FileSystemObject
- c# - 如何在 xUnit 中使用泛型正确模拟扩展方法?
- excel - 根据 DATE 循环浏览文件夹(取剩余日期)VBA
- hibernate - 我可以在 Spring Data JPA 中将 NaN 处理为 NULL 吗?
- jakarta-ee - Java 11 和 javax.rmi.PortableRemoteObject
- go - 如何在 Golang 中通过分隔符拆分字符串