37,743
社区成员




import urllib
import urllib.request
import http.cookiejar
import urllib.parse
import re
#登录的主页面
hosturl = 'http://passport.csdn.net' #自己填写
#post数据接收和处理的页面(我们要向这个页面发送我们构造的Post数据)
posturl = 'https://passport.csdn.net/account/login' #从数据包中分析出,处理post请求的url
#设置一个cookie处理器,它负责从服务器下载cookie到本地,并且在发送请求时带上本地的cookie
cj = http.cookiejar.LWPCookieJar()#创建一个CookieJar实例,用在存储和使用Cookie
cookie_support = urllib.request.HTTPCookieProcessor(cj)#用HTTPCookieProcessor处理获取的Cookie
opener = urllib.request.build_opener(cookie_support, urllib.request.HTTPHandler)#返回一个opener实例
urllib.request.install_opener(opener)#要打开一个url必须安装opener
#打开登录主页面(他的目的是从页面下载cookie,这样我们在再送post数据时就有cookie了,否则发送不成功)
h = urllib.request.urlopen(hosturl)
#正则
html = h.read()
LtRe = re.compile(b'name=\"lt\" value=\"(.*)\"')
Lt = re.findall(LtRe, html)
Lt = Lt[0]
executionRe = re.compile(b'name=\"execution\" value=\"(.*)\"')
exeRe = re.findall(executionRe, html)
exeRe = exeRe[0]
print(Lt)
print(exeRe)
#构造header,一般header至少要包含一下两项。这两项是从抓到的包里分析得出的。
headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0',
'Referer' : 'https://passport.csdn.net/account/login'}
postData = {
'_eventId' : 'submit',
'execution' : exeRe,
'lt' : Lt,
'password' : '****',
'username' : '****'
}
print(postData)
#需要给Post数据编码
postData = urllib.parse.urlencode(postData).encode('utf-8')
#通过urllib2提供的request方法来向指定Url发送我们构造的数据,并完成登录过程
request = urllib.request.Request(posturl, postData, headers)
print(request)
response = urllib.request.urlopen(request)
text = response.read()
print(text)
save_path="D:\\snatch2.txt"
# save_path 's file unnecessary to be exist
f_obj = open(save_path,'wb')
f_obj.write(text)
print("snatch successfully.")