Python 如何在selenium中保留登录状态
我使用selenium和bs4解析网页。网页使用扫描QR码和验证码登录 我使用Python 如何在selenium中保留登录状态,python,html,selenium,authentication,webdriver,Python,Html,Selenium,Authentication,Webdriver,我使用selenium和bs4解析网页。网页使用扫描QR码和验证码登录 我使用WebDriverWait等待用户登录 wait = ui.WebDriverWait(driver, 60) # timeout after 60 seconds, just leave time for user to login wait.until(lambda driver: driver.execute_script('return isLogin();')) 登录后,开始解析工作 它工
WebDriverWait
等待用户登录
wait = ui.WebDriverWait(driver, 60) # timeout after 60 seconds, just leave time for user to login
wait.until(lambda driver: driver.execute_script('return isLogin();'))
登录后,开始解析工作
它工作得很好,只是每次我运行脚本时,它都会打开一个新的broswr窗口,我需要登录
如何在每次运行脚本时保留登录状态以避免登录。有关每次使用cookie时避免登录的信息。 例如:
import pickle
from selenium import webdriver
browser = webdriver.Chrome()
browser.get("http://www.google.com")
pickle.dump(browser.get_cookies(), open("cookies.pkl","wb"))
稍后下载cookie:
import pickle
from selenium import webdriver
browser = webdriver.Chrome()
browser.get("http://www.google.com")
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
browser.add_cookie(cookie)
您可以使用浏览器的默认配置文件
options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=C:\\Path") #Path to your chrome profile
w = webdriver.Chrome(executable_path="C:\\Users\\chromedriver.exe", chrome_options=options)
您可以通过放置
chrome://version/
在浏览器url中。我发现以下两种解决方案
1。使用broser profile(这不适用于打开新窗口时要求登录的站点)
我使用firefox,所以我用这种方式设置配置文件
profile = webdriver.FirefoxProfile('C:/Users/lf/AppData/Roaming/Mozilla/Firefox/Profiles/5fvhqsc9.selenium')
driver = webdriver.Firefox(firefox_profile=profile)
如果要为代码设置单独的配置文件,请在cmd行中使用firefox.exe-p
。参见注意,只需在代码中使用配置文件,不要更改默认的选择配置文件 2。使用cookie(这适用于打开新窗口时要求登录的站点)
参考资料:
当浏览器关闭时,某些站点会清除登录状态。如何处理这种情况?某些网站在浏览器关闭时会清除登录状态。这个案子怎么办?那就行不通了。但大多数网站都有一个“记住我”按钮。使用cookie方法是可行的。但是在你的代码中,你有一些问题。检查的cookie部分。
from selenium import webdriver
from selenium.webdriver.support import ui
import pickle
driver = webdriver.Firefox()
"""
Cookie can be only add to the request with same domain.
When webdriver init, it's request url is `data:` so you cannot add cookie to it.
So first make a request to your url then add cookie, then request you url again.
"""
browser = driver.get('url')
cookies = pickle.load(open("cookies.pkl", "rb"))
for cookie in cookies:
driver.add_cookie(cookie)
browser = driver.get('url')
if driver.execute_script('return !isLogin();'): #[How to access javascript result in selenium](https://stackoverflow.com/q/58620192/6521116)
driver.execute_script('openLoginUI();')
# [How can I make Selenium/Python wait for the user to login before continuing to run?](https://stackoverflow.com/a/16927552/6521116)
wait = ui.WebDriverWait(driver, 60) # timeout after 60 seconds, just leave time for user to login
wait.until(driver.execute_script('return isLogin()'))
pickle.dump(driver.get_cookies(), open("cookies.pkl", "wb"))