Python模拟登陆CSDN出现了一些问题

AHU_Tree 2014-09-07 04:06:39
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.")


查看CSDN登录源码知CSDN会发放WEBFLOW来作为POST
我尝试用正则表达式提取了这里的LT和execution值并构造POST
但是还是提示无法登陆
...全文
240 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
iasky 2014-09-08
  • 打赏
  • 举报
回复
header不够,用firebug看看吧,都加上

37,743

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • WuKongSecurity@BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧