selenium
获取网址的 token 和 cookies调用 selenium
库,启动浏览器
impor time
from icecream import ic
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
# 隐式等待30s
driver.set_page_load_timeout(30)
# 窗口最大化
driver.maximize_window()
# 获取网址
driver.get("需要获取数据的网址")
time.sleep(3)
# 输入用户名密码
driver.find_element(By.ID, 'username').send_keys('用户名')
driver.find_element(By.ID, 'password').send_keys('密码')
# 获取 token 值
token = driver.execute_script('return localStorage.getItem("AuthToken");')
# ic(f"\n{token}")
# 保持至本地txt文件
with open("token.txt", "w") as t:
t.write(f"{token}")
t.close()
# 获取 cookies
dict_cookies = driver.get_cookies()
# ic(json.dumps(dict_cookies))
# 保存至 json 文件
with open("cookies.json", "w") as c:
c.write(f"{dict_cookies}")
# 将获取的 cookies 值并保持至本地txt文件
cookies = {}
for s in dict_cookies:
cookies[s['name']] = s['value']