问题描述
- python模拟twitter登陆
- 这是我的代码,不知道为什么一直无法成功
import urllib2
import urllib
import cookielib
import reclass Fetcher(object):
def init(selfname=Nonepwd=None):
self.cj = cookielib.LWPCookieJar() #获取一个保存cookie的对象。
self.cookie_processor = urllib2.HTTPCookieProcessor(self.cj) #将一个保存cookie对象,和一个HTTP的cookie的处理器绑定
self.opener = urllib2.build_opener(self.cookie_processor urllib2.HTTPHandler) #创建一个opener,将保存了cookie的http处理器,设置一个handler用于处理http的URL的打开
urllib2.install_opener(self.opener) #将包含了cookie、http处理器、http的handler的资源和urllib2对象绑定在一起
self.name = name
self.pwd = pwd
self.hosturl = 'https://twitter.com/' #登录的主页面self.posturl = 'https://twitter.com/sessions' #post数据接收和处理的页面(我们要向这个页面发送我们构造的Post数据)
def login(self): #跳转到登陆界面,此时可获得cookie req=urllib2.Request(self.hosturl) resp=urllib2.urlopen(req) html = resp.read() #得到表单中的authenticity_token att=re.compile('value=""(.*?)"" name=""authenticity_token""') t = att.search(html) authenticity_token = t.group(1) #处理cookie #cookies = '' #for index cookie in enumerate(self.cj): # cookies = cookies+cookie.name+""=""+cookie.value+"";""; #cookie = cookies[:-1] #print ""cookies:""cookie #request headers,仿冒浏览器 self.header = {#':host': 'twitter.com' #':method': 'POST' #':path': '/sessions' #':scheme': 'https' #':version': 'HTTP/1.1' #'accept': 'text/htmlapplication/xhtml+xmlapplication/xml;q=0.9image/webp*/*;q=0.8' #'accept-encoding': 'gzipdeflatesdch' #'accept-language': 'zh-CNzh;q=0.8' # 'cache-control': 'max-age=0' # #'content-length': '214' #'content-type': 'application/x-www-form-urlencoded' # 'cookie': cookie #'origin': 'https://twitter.com' 'referer': 'https://twitter.com/' 'user-agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML like Gecko) Chrome/31.0.1650.63 Safari/537.36' } #print(self.cj) #form data,提交的表单数据 postForm = {'session[username_or_email]':self.name 'session[password]':self.pwd 'remember_me':'1' 'return_to_ssl':'true' 'scribe_log':'' 'redirect_after_login':'/' 'authenticity_token':authenticity_token } postData=urllib.urlencode(postForm) #编码 #print(postData) #提交表单 rep = urllib2.Request(self.posturlpostFormself.header) resp=urllib2.urlopen(req) html = resp.read() print(html) #req=urllib2.Request(self.hosturl) #resp=urllib2.urlopen(req) #html = resp.read() #print(html)
if name == '__main__':
username = '*******' #用户名
password = '******' #密码
fet = Fetcher(usernamepassword);
fet.login()大神帮忙看看吧。
我的思路和网上的思路一样的,我是个菜鸟,也没什么币,希望大家见谅了
解决方案
你可以试试 requests库。
http://www.python-requests.org/en/latest/user/advanced/#session-objects
做登录主要是状态同步的问题。这个库封装的比较好。
解决方案二:
不怎么会发帖,大家将就看吧
解决方案三:
先看看返回的错误信息,比如是认证没过还是网络不通等
解决方案四:
已经调试好了
一个是
rep = urllib2.Request(self.posturlpostFormself.header)
resp=urllib2.urlopen(req)
参数写错了,还有就是第一句不能加header,估计header参数有问题,去掉header就好了。
谢谢大家了