Skip to content

Instantly share code, notes, and snippets.

@dkuebric
Created December 28, 2011 19:16
Show Gist options
  • Save dkuebric/1529242 to your computer and use it in GitHub Desktop.
Save dkuebric/1529242 to your computer and use it in GitHub Desktop.
multi-mechanize/reddit: forms, cookies, and comments
import mechanize
import urllib
BASE_URL = 'http://my-reddit'
THREAD = BASE_URL + '/r/reddit/particular-thread'
class Transaction(object):
def __init__(self):
self.user = 'redditor'
self.pass = 'password'
def run(self):
# init browser
br = mechanize.Browser()
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)
# do login
_ = br.open(BASE_URL)
br.select_form(nr=1)
br.form['user'] = self.user
br.form['passwd'] = self.pass
r = br.submit()
r.read()
assert (r.code == 200), 'Bad HTTP Response'
# go to comment page
posting = THREAD
rval = THREAD.split('/')[4]
r = br.open(posting)
r.read()
assert (r.code == 200), 'Bad HTTP Response'
# load required value from hidden form field
br.select_form(nr=0)
uh = br.form['uh']
# select top-level comment form
br.select_form(nr=12)
thing_id = br.form['thing_id']
id = '#' + br.form.attrs['id']
# build and submit the comment posting
data = {'uh':uh, 'thing_id':thing_id, 'id':id, 'renderstyle':'html', 'r':rval, 'text':"This is such an interesting comment! Upboat me! x"}
new_data_dict = dict((k, urllib.quote(v).replace('%20', '+')) for k, v in data.iteritems())
new_data = 'thing_id=%(thing_id)s&text=%(text)s&id=%(id)s&r=%(r)s&uh=%(uh)s&renderstyle=%(renderstyle)s' %(new_data_dict)
r = br.open(BASE_URL + '/api/comment', new_data)
r.read()
assert (r.code == 200), 'Bad HTTP Response'
if __name__ == '__main__':
trans = Transaction()
trans.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment