前言:由于登录反爬措施的越来越麻烦,甚至出现了12306这种看图识物的无敌验证码,我只能说,我选择死亡。这就衍生出了使用selenium来获取获取cookies。
实例:获取qq空间cookies,亲测成功2018-3-7
from selenium import webdriver import requests import json import time
1 def get_cookies(): 2 browser = webdriver.Chrome(executable_path="D:\SeleniumDemo-master\chromedriver.exe") 3 browser.get("https://user.qzone.qq.com/xxx/infocenter")# xxx 改为qq账号 4 input("请登陆后按Enter") 5 #print(browser.get_cookies()) 6 cookie={} 7 for i in browser.get_cookies(): 8 cookie[i["name"]] = i["value"] 9 with open("cookies.txt","w") as f: 10 f.write(json.dumps(cookie)) 11 # time.sleep(5) 12 # button = browser.find_element_by_xpath(‘//*[@id="switcher_plogin"]‘) 13 # button.click() 14 15 #browser.close() 16 def get_content(): 17 user_agent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36" 18 with open("cookies.txt","r")as f: 19 cookies = f.read() 20 cookies = json.loads(cookies) 21 session = requests.session() 22 html = session.get("https://user.qzone.qq.com/xxx/infocenter",headers={"User-Agent":user_agent},cookies=cookies) # xxx改为qq账号 23 print(html.text) 24 25 if __name__ == "__main__": get_cookies() get_content()
cookies一保存,至少短期内是可以省下登录的时间。
原文地址:https://www.cnblogs.com/zenan/p/8522666.html
时间: 2024-11-08 00:04:07