Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Here's a conversation I just had with this. First attempt, no manual modifications needed. Granted it's pretty simple procedure, but it worked perfectly the first time.

Me: Write me a Python function that fetches the title of the first 5 most recent posts on Hacker News.

Response:

Here is a Python function that will fetch the titles of the first 5 most recent posts on Hacker News:

    import requests

    def fetch_hacker_news_titles():
        response = requests.get('https://hacker-news.firebaseio.com/v0/newstories.json')
        stories = response.json()[:5]
        titles = []

        for story in stories:
            data = requests.get(f'https://hacker-news.firebaseio.com/v0/item/{story}.json')
            title = data.json()['title']
            titles.append(title)

    return titles

You can then call the function like this:

    titles = fetch_hacker_news_titles()
I fired this up in a replit.com session to test, and lo and behold it worked. Here was the output:

    ['Getting bus priority right. Lessons from Bologna', "Here's Who helped Elon Musk buy Twitter", 'Embodying Heaven: Frankincense and Myrrh and Their Connection to Divinity', 'The Great Forgetting', 'Sell Everything (2013)']

I verified by checking the 'new' tab, and this was accurate at the time I ran this. Not bad!

Edit: Fix my HN code formatting mistakes.



Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: