我正在尝试使用 python、selenium 和 chrome 登录以下页面:
您不需要我的用户名和密码来重现此场景。使用虚构的用户名和密码,效果是一样的。如果我打开一个“普通”chrome 窗口(因此不使用 selenium)并尝试使用任何用户名/密码登录(假设它不正确),您会收到“无效的用户名/密码”错误。
如果我尝试使用 python selenium 和 chrome 登录并使用我的用户名/密码,我会收到一条错误消息,提示“发生错误,请重试”。
网页因此识别selenium并且不让我进入。我能做什么?在使用 selenium 和 chrome 时我也希望这个“无效的用户名/密码”,这样我就可以使用正确的用户名和密码登录
提前致谢!
您无法使用普通的 chromedriver 登录,但幸运的是您有两个选择:
使用
pip install undetected-chromedriver
(文档)安装它,然后运行
import undetected_chromedriver as uc
driver = uc.Chrome()
driver.get(url)
# do stuff to log in
或者,您可以使用普通的 chromedriver 并加载您已登录的用户配置文件。使用此方法,当您运行
driver.get(url)
时,您将已经登录,因为它使用用户配置文件的 cookie。 在这里您可以找到有关如何创建用户配置文件并将其加载到 chromedriver 中的教程
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=C:\\Users\\username\\AppData\\Local\\Google\\Chrome\\User Data")
options.add_argument("profile-directory=Profile 2")
driver = webdriver.Chrome(..., options=options)
driver.get(url)
# now you are already logged in
我在另一个网站上遇到了同样的问题,我无法使用硒登录。我发现您可以在命令提示符中使用指定的端口启动 Google Chrome,然后您可以“连接到”(抱歉,我不是这方面的专家,所以我的术语可能是错误的),它解决了我的问题。
我使用的代码是:
from os import getcwd
from pyspark import SparkContext
from selenium.webdriver import Chrome, ChromeOptions
from selenium.webdriver.chrome.service import Service
from subprocess import Popen
from winreg import OpenKey, HKEY_LOCAL_MACHINE, EnumValue
#Service Manager automatically updates chromedriver
service = Service()
#Gets path of 'chrome.exe' on your computer
chrome_folder_path = EnumValue(OpenKey(HKEY_LOCAL_MACHINE, r"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe"), 0)[1]
url = "your url"
#Important argument here is the port '9229'
args = f'--remote-debugging-port=9229 --user-data-dir="{getcwd()}/chromeprofile" --disable-gpu --start-maximized --log-level=3 --disable-extensions' #--headless
#Launches Google chrome with the desired url and args
Popen(f'{chrome_folder_path} {url} {args}')
sleep(2)
#I'm sorry for not being able to explain this but essentially it connects to the port 9229 and making you able to control the browser with selenium
sc = SparkContext()
sc.setLogLevel("OFF")
sc.setSystemProperty("webdriver.chrome.driver", rf"chromedriver.exe");
chrome_options = ChromeOptions()
chrome_options.add_experimental_option("debuggerAddress", "localhost:9229")
global driver
driver = Chrome(service=service, options=chrome_options)
我知道我的代码离理想还很远,但我希望它至少能在某种程度上帮助你。