利用requests 模擬登陸csdn

環境:python3.6.1 + lxml4.0.0 + requests2.18.4

坑一:登陸時請求的網址需要構造,數據在form標籤屬性裏,
坑二:表單數據的提取
坑三:登陸後的跳轉,不然無法訪問個人主頁

import requests
from lxml import etree


#設置session
s=requests.Session()

#基礎參數
url='https://passport.csdn.net'
headers={'Host':'passport.csdn.net',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:55.0) Gecko/20100101 Firefox/55.0',
'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language':'zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3',
'Referer': 'https://passport.csdn.net/?service=http://write.blog.csdn.net/postedit'
}

#抓取post參數和jsessionid
f=s.get(url,headers=headers).content.decode('utf-8')
p=etree.HTML(f)
it=p.xpath("//input[@name='lt']/@value")
exe=p.xpath("//input[@name='execution']/@value")
eventId=p.xpath("//input[@name='_eventId']/@value")
jid=p.xpath("//form/@action")
jid=str(jid[0])

#提取postdata#
d={'username':'[email protected]',
    'password':'1005931665asd'}
d['lt']=str(it[0])
d['execution']=str(exe[0])
d['_eventId']=str(eventId[0])
#構造post url
url=url+jid

#進行登陸
gg=s.post(url,data=d,headers=headers)
#重定向
tt=s.get("http://www.csdn.net/")
print(tt.status_code)
#進入個人主頁
hh=s.get("http://write.blog.csdn.net/postlist").content.decode('utf-8')
print(hh)


發佈了25 篇原創文章 · 獲贊 12 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章