Search code examples
pythonfacebookfacebook-graph-apimechanize

How to edit a facebook post in Python?


I have a post on my fb page which I need to update several times a day with data elaborated in a python script. I tried using Selenium, but it gets often stuck when saving the post hence the script gets stuck too, so I'm trying to find a way to do the job within python itself without using a web browser.

I wonder is there a way to edit a FB post using a python library such as Facepy or similar?

I'm reading the graph API reference but there are no examples to learn from, but I guess first thing is to set up the login. On the facepy github page is written that

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

I tried logging in with 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')

but it gives this error

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

I also tried with 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()

but it gives an error too

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

Solution

  • Install the facebook package

    pip install facebook-sdk
    

    then to update/edit a post on your page just run

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