Skip to content
Advertisement

Scraping from beautifulsoup in Python with a for loop just returns the last result

I’m trying to scrape data from a webpage using beautifulsoup and (ultimately) output it into a csv. As a first step in this, I’ve tried to get the text of the relevant table. I managed to do this, but the code no longer gives me the same output when I rerun it: instead of returning all 12372 records when I run the for loop, it just saves the last one.

An abbreviated version of my code is:

JavaScript

But the for loop only saves the text for the last (ie 12372nd) element in the table. Do I need to do something else in order for it to save each element when it loops through? I think my previous (desired) output had the text of each element on a new line.

This is my first time using python, so apologies if I’ve made an obvious mistake.

Advertisement

Answer

What you’re doing is overwriting your birthText string each iteration, so by the time it gets to the end only the last one will be saved. To solve this, create a list and append each line:

JavaScript

Or, more concisely:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement