selenium如何保留cookies
时间: 2023-08-14 19:09:43 浏览: 300
可以使用pickle库来保存和加载cookies。首先,在登录成功后,使用pickle.dump()函数将cookies保存到一个文件中,例如'cookies.pkl'。下次访问网站时,可以使用pickle.load()函数加载之前保存的cookies文件。然后,使用driver.add_cookie()方法将cookies添加到浏览器中。这样就可以保留cookies了。
以下是一个示例代码:
```python
import pickle
from selenium import webdriver
# 登录成功后保存cookies
cookies = driver.get_cookies()
pickle.dump(cookies, open('cookies.pkl', 'wb'))
# 下次访问加载cookies
cookies = pickle.load(open('cookies.pkl', 'rb'))
for cookie in cookies:
driver.add_cookie(cookie)
# 打印加载成功信息
print('载入cookies成功')
```
这样,使用selenium就可以保留cookies了。
#### 引用[.reference_title]
- *1* [selenium如何保存网站的cookie,方便下一次自动登录](https://blog.csdn.net/huangbangqing12/article/details/124760021)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* *3* [Python selenium中保存、读取登陆后的cookie详细说明](https://blog.csdn.net/xhaimail/article/details/104641428)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文