用selenium获取cookies
前言:由于登录反爬措施的越来越麻烦,甚至出现了12306这种看图识物的无敌验证码,我只能说,我选择死亡。这就衍生出了使用selenium来获取获取cookies。
实例:获取qq空间cookies,亲测成功2018-3-7(注意点:chromedriver.exe的路径输入)
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一保存,至少短期内是可以省下登录的时间。
改进:(自动填写账号密码)
1 def get_cookies(): 2 """获取cookies保存为txt""" 3 browser = webdriver.Chrome(executable_path="D:\SeleniumDemo-master\chromedriver.exe") 4 browser.get("https://user.qzone.qq.com/") 5 6 #input("请登陆后按Enter") 7 browser.switch_to.frame("login_frame") 8 button = browser.find_element_by_css_selector('#switcher_plogin') 9 button.click() 10 account = browser.find_element_by_css_selector("#u") 11 account.clear() 12 account.send_keys("") #此处写账号 13 14 password = browser.find_element_by_css_selector("#p") 15 password.clear() 16 password.send_keys("") #此处写密码 17 18 login_button = browser.find_element_by_css_selector("#login_button") 19 login_button.click() 20 #print(browser.get_cookies()) 21 22 cookie={} 23 for i in browser.get_cookies(): 24 cookie[i["name"]] = i["value"] 25 with open("cookies.txt","w") as f: 26 f.write(json.dumps(cookie)) 27 input() 28 #browser.close()