Posting to Hacker News Programmatically

If you run this snippet of Python code, it will submit this “Snippet” (the one you’re currently reading) to Hacker News.

from html.parser import HTMLParser
import getpass
import requests
import time

    ''  # Put your Hacker News username here.
    or getpass.getuser()  # (But if you don't, we'll try a sensible default.)
    ''  # We'll prompt you for your password, or you can enter it here.
    or getpass.getpass()
# You can reconfigure the title and url to submit here.
TITLE_TO_SUBMIT = 'Posting to Hacker News Programmatically'

# Login
session = requests.Session()
        'acct': USERNAME,
        'pw': PASSWORD,

# Get the CSRF token ("FNID")
class FNIDExtractor(HTMLParser):
  fnid = None
  def handle_starttag(self, tag, attrs):
    if tag.lower() == 'input' and ('name', 'fnid') in attrs:
      self.fnid = dict(attrs)['value']
f = FNIDExtractor()
submit_response = session.get('')

# Submit
        'title': TITLE_TO_SUBMIT,
        'url': URL_TO_SUBMIT,
        'fnid': f.fnid,

You can change the title and URL before running this to make a new submission, or run it as is to submit this snippet.

If you try to submit a URL that’s already been submitted recently – such as this snippet – it won’t submit a second time, so no harm done in running this.

To learn more about sessions and see why this works, you can read about them in the requests documentation.

Discussion 💬