当我运行代码时,它运行没有错误,但我注意到它确实没有登录到Facebook并发布一个帖子“Hello world”。一旦它被登录,从未在之后。 我使用了图形API。
很想得到一些帮助。感谢
import urllib2, cookielib, re, os, sys
from facepy import GraphAPI
import facebook
class Facebook:
def __init__(self, email, password):
self.email = email
self.password = password
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.add_headers = [('Referer', 'http://login.facebook.com/login.php'),
('Content-Type', 'application/x-www-form-urlencoded'),
('User-Agent', 'Mozilla/8.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'
data = "locale=en_US&non_com_login=&email=" + self.email + "&pass="+ self.password + "&lsd=20TOl"
usock = self.opener.open('https://www.facebook.com/')
usock = self.opener.open(url, data)
read = usock.read()
if "Logout" in read:
print "Logged in."
graph = facebook.GraphAPI(Access Token)
graph.put_object("me", "feed", post="Hello, World!")
else:
print "failed login"
print read
sys.exit()
print read
f = Facebook("email", "password")
f.login()
nik = graph.fql('select uid, name, friends from user where uid in'
'(select first_name, middle_name, last_name '
'from friend where uid1 = me())')
print nik
答案 0 :(得分:0)
我建议你查看一些facebook文档,可能有一个API。但无论如何我试图用facebook请求登录facebook,但这很痛苦。如果你的目标只是轻松登录到facebook,你可以简单地使用selenium的webdriver,它工作正常。 这是一个可能让你开始的片段:
from selenium import webdriver
EMAIL='yourmail'
PASSWORD='yourpassword'
url = 'https://de-de.facebook.com/login/'
driver = webdriver.PhantomJS()
# driver = webdriver.Firefox()
driver.get(url)
driver.find_element_by_id('email').send_keys(EMAIL)
driver.find_element_by_id('pass').send_keys(PASSWORD)
driver.find_element_by_id('loginbutton').submit()
出于测试目的,您可以使用webdriver.Firefox()
代替PhantomJS()
登录后,您还可以切换到请求会话,这可能会更快。 (因此您需要import requests
)
session = requests.session()
cook = {i['name']: i['value'] for i in driver.get_cookies()}
#transfer cookies to new session
requests.utils.add_dict_to_cookiejar(session.cookies, cook)
driver.quit()