python模拟twitter登陆

代码港湾 论文问答 1

这是我的代码,不知道为什么一直无法成功

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/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
              #'accept-encoding': 'gzip,deflate,sdch',
              #'accept-language': 'zh-CN,zh;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.posturl,postForm,self.header)
    resp=urllib2.urlopen(req)
    html = resp.read()
    print(html)
    #req=urllib2.Request(self.hosturl)
    #resp=urllib2.urlopen(req)
    #html = resp.read()
    #print(html)

回复

共1条回复 我来回复

发表回复

登录后才能评论