所以我使用Python Selenium web驱动程序,我的问题是我不知道如何生成web cookie,然后将其保存/导出到.txt文件?
我尝试了很多方法,但都没用:/
要在硒中生成cookie,请使用driver.add_cookie()
。要从网站获取所有可用的cookie,请使用driver.get_cookies()
最终代码:(包括将cookie保存在txt文件中(
from selenium import webdriver
driver = webdriver.Chrome()
# Navigate to url
driver.get("http://www.example.com")
# Add the cookies you want
driver.add_cookie({"name": "test1", "value": "cookie1"})
driver.add_cookie({"name": "test2", "value": "cookie2"})
# Get all available cookies
cookies = driver.get_cookies()
print(cookies)
# Open file
f = open("cookies.txt", "a")
for cookie in cookies:
f.write(str(cookie)+"n")
f.close()
TXT文件输出:
{'domain': 'www.example.com', 'httpOnly': False, 'name': 'test2', 'path': '/', 'secure': False, 'value': 'cookie2'}
{'domain': 'www.example.com', 'httpOnly': False, 'name': 'test1', 'path': '/', 'secure': False, 'value': 'cookie1'}
更新:
读取文件并获取所有保存的cookie的代码:
import json
import ast
# Open and read the file:
f = open("cookies.txt", "r")
# Remove line breaks
list = f.read().split("n")
for cookie in list:
print(ast.literal_eval(cookie)["value"]) # Convert output into dictionary and print cookie value
...