python - 如何在 Python 中编辑 Facebook 帖子?

标签 python facebook facebook-graph-api mechanize

我的 fb 页面上有一个帖子,我需要每天更新几次,其中包含在 Python 脚本中详细说明的数据。我尝试使用 Selenium,但是在保存帖子时它经常卡住,因此脚本也卡住了,所以我试图找到一种方法来在 python 本身中完成这项工作,而无需使用 Web 浏览器。
我想知道有没有办法使用诸如 Facepy 或类似的 Python 库来编辑 FB 帖子?
我正在阅读 graph API引用但是没有可以学习的例子,但我想第一件事是设置登录。在脸谱上 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
我也试过 Mechanize
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'

最佳答案

安装 facebook 包裹

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')

关于python - 如何在 Python 中编辑 Facebook 帖子?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65081429/

相关文章:

facebook - 将 Facebook Scraper 重定向到/?_escaped_fragment_=,使用 HTML5 历史 URL(无 hashbang)获取 AJAX 内容

iphone - 如何查找 Gmail 和 Facebook 帐户的所有事件 session ?

python - 使用 Pandas 替换不同列的元素

python - 多个函数更改的全局变量——如何在 Python 中声明

linux - 带有 FBCTF 的虚拟机

jquery - 将 Jquery 与 facebook JS SDK 结合使用

python - Celery 在其他任务完成时启动任务

python - 在 numpy/pandas 中生成相关数

android - 如何通过 Facebook Android SDK 向好友发送应用请求

facebook - 通过通知 API 从应用程序向用户发送通知