If I run the following code 10 times in a row, it will work about half the time and fail the rest. Anyone know why?
import urllib2, cookielib, re, os, sys class Facebook(): def __init__(self, email, password): self.email = email self.password = password cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) opener.addheaders = [('Referer', 'http://login.facebook.com/login.php'), ('Content-Type', 'application/x-www-form-urlencoded'), ('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 (.NET CLR 3.5.30729)')] self.opener = opener def login(self): url = 'https://login.facebook.com/login.php?login_attempt=1' data = "locale=en_US&non_com_login=&email="+self.email+"&pass="+self.password+"&lsd=20TOl" usock = self.opener.open('http://www.facebook.com') usock = self.opener.open(url, data) if "Logout" in usock.read(): print "Logged in." else: print "failed login" print usock.read() sys.exit() f = Facebook("test@gmail.com", "asdfasdf") f.login()
小智.. 16
所以我尝试了你的代码,并让它登录一次,然后像你一样我再次登录时遇到问题.在'if'语句之前的一行上,我添加了print usock.read()并最终获得了一堆html代码.然后我将该代码放入记事本中,将其保存为html文件,然后将其拉出来.这就是正在发生的事情:Facebook怀疑我们是从计算机程序登录的,并且正在等待我们通过显示验证字来验证我们是否真实.该程序没有考虑到这一点,并且当它真的更多是挂起登录时打印"登录失败".
所以我尝试了你的代码,并让它登录一次,然后像你一样我再次登录时遇到问题.在'if'语句之前的一行上,我添加了print usock.read()并最终获得了一堆html代码.然后我将该代码放入记事本中,将其保存为html文件,然后将其拉出来.这就是正在发生的事情:Facebook怀疑我们是从计算机程序登录的,并且正在等待我们通过显示验证字来验证我们是否真实.该程序没有考虑到这一点,并且当它真的更多是挂起登录时打印"登录失败".
我遇到了同样的问题.我找到的唯一解决方案是... facebook mobile更稳定.
class Acc: jar = cookielib.CookieJar() cookie = urllib2.HTTPCookieProcessor(jar) opener = urllib2.build_opener(cookie) headers = { "User-Agent" : "Mozilla/5.0 (X11; U; FreeBSD i386; en-US; rv:1.8.1.14) Gecko/20080609 Firefox/2.0.0.14", "Accept" : "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,text/png,*/*;q=0.5", "Accept-Language" : "en-us,en;q=0.5", "Accept-Charset" : "ISO-8859-1", "Content-type": "application/x-www-form-urlencoded", "Host": "m.facebook.com" } def login(self): try: params = urllib.urlencode({'email':'test@test.test','pass':'dempassword','login':'Log+In'}) req = urllib2.Request('http://m.facebook.com/login.php?m=m&refsrc=m.facebook.com%2F', params, self.headers) res = self.opener.open(req) html = res.read() #print res.getheader('location').split('/')[3] except urllib2.HTTPError, e: print e.msg except urllib2.URLError, e: print e.reason[1] return False def fetch(self,url): req = urllib2.Request(url,None,self.headers) res = self.opener.open(req) return res.read() bla = Acc() bla.login()
此外,Facebook移动版没有填充ajax,因此搞清楚要求制作的内容要容易得多.