如何用Python编辑facebook帖子?

2024-04-24 15:58:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我在我的fb页面上有一篇帖子,我需要每天用python脚本详细描述的数据更新几次。我尝试使用Selenium,但它在保存文章时经常会卡住,因此脚本也会卡住,因此我试图找到一种方法,在python内部完成这项工作,而不使用web浏览器

我想知道有没有一种方法可以使用诸如Facepy或类似的python库来编辑FB帖子

我正在阅读graph API引用,但是没有可以学习的示例,但是我想第一件事是设置登录。在facepy github页面上写着

note that Facepy does not do authentication with Facebook; it only consumes its API. To get an access token to consume the API on behalf of a user, use a suitable OAuth library for your platform

我试着用BeautifulSoup登录

from bs4 import BeautifulSoup
import requests
import re

def facebook_login(mail, pwd):
session = requests.Session()
r = session.get('https://www.facebook.com/', allow_redirects=False)
soup = BeautifulSoup(r.text)
action_url = soup.find('form', id='login_form')['action']
inputs = soup.find('form', id='login_form').findAll('input', {'type': ['hidden', 'submit']})
post_data = {input.get('name'): input.get('value')  for input in inputs}
post_data['email'] = mail
post_data['pass'] = pwd.upper()
scripts = soup.findAll('script')
scripts_string = '/n/'.join([script.text for script in scripts])
datr_search = re.search('\["_js_datr","([^"]*)"', scripts_string, re.DOTALL)
if datr_search:
    datr = datr_search.group(1)
    cookies = {'_js_datr' : datr}
else:
    return False
return session.post(action_url, data=post_data, cookies=cookies, allow_redirects=False)

facebook_login('email', 'psw')

但它给出了这个错误

action_url = soup.find('form', id='login_form')['action']
TypeError: 'NoneType' object is not subscriptable

我也试过机械化

import mechanize

username = 'email'
password = 'psw'
url = 'http://facebook.com/login'

print("opening browser")
br = mechanize.Browser()
print("opening url...please wait")
br.open(url)
print(br.title())
print("selecting form")
br.select_form(name='Login')
br['UserID'] = username
br['PassPhrase'] = password
print("submitting form"
br.submit()
response = br.submit()
pageSource = response.read()

但它也给出了一个错误

mechanize._response.httperror_seek_wrapper: HTTP Error 403: b'request disallowed by robots.txt'

Tags: brimportformurlinputdatagetfacebook
1条回答
网友
1楼 · 发布于 2024-04-24 15:58:15

安装^{}

pip install facebook-sdk

然后,要更新/编辑页面上的帖子,只需运行

import facebook

page_token = '...'
page_id = '...'
post_id = '...'
fb = facebook.GraphAPI(access_token = page_token, version="2.12")
fb.put_object(parent_object=page_id+'_'+post_id, connection_name='', message='new text')

相关问题 更多 >