Python Selenium将继续登录到网站

2024-05-03 22:44:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行一个简单的scrape代码,从一个网站上抓取几行代码。问题是Python总是打开一个新的Chrome窗口,每次我运行bot时都会再次登录

因此,我在线阅读并创建了一个Chrome个人资料。现在它打开了Chrome配置文件,但它仍然要求我登录该网站。我想我需要保存饼干。我尝试了一些YouTube教程,但我不知道如何保存cookies。我是个彻头彻尾的傻瓜,有人能告诉我怎么做吗

这是我的代码:

options = Options() 
options.add_argument("user-data-dir=C:\\Users\\user\\AppData\\Local\\Google\\Chrome\\User Data\\Profile 2")
driver = webdriver.Chrome(executable_path=r'C:\Program Files (x86)\chromedriver.exe', chrome_options=options)
driver.get("https://websitetologin.com")

search = driver.find_element_by_name("fm-login-id")
search.send_keys("loginemail")
search.send_keys(Keys.RETURN)

time.sleep(3)
search = driver.find_element_by_name("fm-login-password")
search.send_keys("loginpassword")
search.send_keys(Keys.RETURN)

time.sleep(3)

search = driver.find_element_by_class_name("fm-button")
search.send_keys(Keys.RETURN)
time.sleep(3)

1条回答
网友
1楼 · 发布于 2024-05-03 22:44:07

您也可以使用chrome选项user-data-dir=selenium

options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(options =options)

它将为当前会话保存cookies,稍后可用于配置文件和文件夹

你可以在这里查阅for more

driver.get('http://google.com')
for cookie in cookies:
    driver.add_cookie(cookie)

相关问题 更多 >