【发布时间】:2019-09-16 22:41:56
【问题描述】:
我正在尝试让 Selenium 浏览器保持打开状态并等待传递新信息。我正在使用网络服务器将 url 参数发送到我的计算机,这会触发 Selenium 脚本以每次启动一个新实例。问题是我正在访问的网站要求我在每次加载网站时登录,并且每 10 分钟最多登录 3 次。
有没有一种方法可以启动 selenium 浏览器,保持实例打开,然后通过网络服务器传递新参数以利用浏览器实例?
【问题讨论】:
我正在尝试让 Selenium 浏览器保持打开状态并等待传递新信息。我正在使用网络服务器将 url 参数发送到我的计算机,这会触发 Selenium 脚本以每次启动一个新实例。问题是我正在访问的网站要求我在每次加载网站时登录,并且每 10 分钟最多登录 3 次。
有没有一种方法可以启动 selenium 浏览器,保持实例打开,然后通过网络服务器传递新参数以利用浏览器实例?
【问题讨论】:
如果登录会话到期是问题,那么您可以使用 cookie:
您可以在登录后使用此功能保存浏览器cookie:
import logging
def save_cookies(driver, store_cookies_file):
cookies = []
try:
cookies = driver.get_cookies()
with open(store_cookies_file, 'w') as file:
file.write(json.dumps(cookies))
print('Cookies saved to JSON file')
except Exception as e:
print('Could not save cookies to file')
logging.exception(e)
return cookies # return the cookies just in case you want to use them without reading from the saved file
稍后当您想要访问已登录的网站时,您只需加载网站、注入 cookie 并重新加载,您就会发现自己使用之前的会话登录了
这是一个注入 cookie 的函数:
import logging
def add_login_cookies(driver, cookies):
try:
if cookies:
for cookie in cookies:
driver.add_cookie(cookie)
print('Added Cookies')
else:
raise ValueError("No Cookies Passed !")
except Exception as e:
print("Could not add login cookies")
logging.exception(e)
你要做的是:
### SAVING COOKIES
driver.get('website.url')
....
your code to login
....
cookies = save_cookies(driver, "/path/to/store/cookies.json")
### USING THEM LATER
driver.get('website.url')
add_login_cookies(driver, cookies) # if the cookies varibale isn't accessible, read the cookies from the file you stored them in before
driver.refresh() # or use directly driver.get if you want to access a specific page in the website
【讨论】: