1. 程式人生 > >用selenium獲取cookies

用selenium獲取cookies

lose 實例 zone main button get ive cli win

前言:由於登錄反爬措施的越來越麻煩,甚至出現了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一保存,至少短期內是可以省下登錄的時間。

用selenium獲取cookies