用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():
browser = webdriver.Chrome(executable_path="D:\SeleniumDemo-master\chromedriver.exe")
browser.get("https://user.qzone.qq.com/xxx/infocenter")# xxx 改为qq账号
input("请登陆后按Enter")
#print(browser.get_cookies())
cookie={}
for i in browser.get_cookies():
cookie[i["name"]] = i["value"]
with open("cookies.txt","w") as f:
f.write(json.dumps(cookie))
# time.sleep(5)
# button = browser.find_element_by_xpath('//*[@id="switcher_plogin"]')
# button.click() #browser.close()
def get_content():
user_agent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36"
with open("cookies.txt","r")as f:
cookies = f.read()
cookies = json.loads(cookies)
session = requests.session()
html = session.get("https://user.qzone.qq.com/xxx/infocenter",headers={"User-Agent":user_agent},cookies=cookies) # xxx改为qq账号
print(html.text) if __name__ == "__main__":
    get_cookies()
    get_content()

cookies一保存,至少短期内是可以省下登录的时间。

改进:(自动填写账号密码)

 def get_cookies():
"""获取cookies保存为txt"""
browser = webdriver.Chrome(executable_path="D:\SeleniumDemo-master\chromedriver.exe")
browser.get("https://user.qzone.qq.com/") #input("请登陆后按Enter")
browser.switch_to.frame("login_frame")
button = browser.find_element_by_css_selector('#switcher_plogin')
button.click()
account = browser.find_element_by_css_selector("#u")
account.clear()
account.send_keys("") #此处写账号 password = browser.find_element_by_css_selector("#p")
password.clear()
password.send_keys("") #此处写密码 login_button = browser.find_element_by_css_selector("#login_button")
login_button.click()
#print(browser.get_cookies()) cookie={}
for i in browser.get_cookies():
cookie[i["name"]] = i["value"]
with open("cookies.txt","w") as f:
f.write(json.dumps(cookie))
input()
#browser.close()
上一篇:【转】HashMap的工作原理


下一篇:yyy loves Easter_Egg I(恶心的字符串模拟)