r/PythonLearning • • 2d ago

Beginner struggling with web scraping multiple Wikipedia pages using BeautifulSoup in Spyder

Hi everyone!

I'm fairly new to Python and currently learning web scraping using Spyder, BeautifulSoup, and requests.

I've been trying to write a script that extracts data from a Wikipedia table, collects the links from the table, and then visits each link to scrape the corresponding Wikipedia article.

I've managed to get some parts working, but I'm struggling to figure out whether my approach is correct and if there are any mistakes in my code.

I'm particularly unsure about how I'm extracting the links and downloading the individual pages.

I would really appreciate some guidance on how to troubleshoot this or improve my approach.

I'm not looking for someone to write the code for me, just some explanations or pointers so I can understand what I'm doing wrong.

Thanks in advance!

here's the code:

import requests

from bs4 import BeautifulSoup

import os

import time

from urllib.parse import urljoin

import pandas as pd

headers = {

"User-Agent": "AcademyAwardsStudentProject/1.0 (educational research)"

}

resp = requests.get(

"https://en.wikipedia.org/wiki/List_of_Academy_Award%E2%80%93winning_films",

headers=headers,

timeout=30

)

resp.raise_for_status()

soup = BeautifulSoup(resp.text, "html")

table_list = soup.find_all("table")

print(len(table_list))

for index, table_name in enumerate(table_list):

if "Film" in table_name.text:

print(index, table_name)

class_name="wikitable"

table_list = soup.find_all("table", class_=class_name)

#print(len(table_list), *[i.text for i in table_list])

for table in table_list:

if "Film" in table.text and "Nominations" in table.text:

table_data = table

break

table_headers = table_data.find_all("th")

column_headers = []

for header in table_headers:

column_headers.append(header.text.strip())

table_row_data = []

for row in table_data.find_all("tr"):

individual_data = [i.text.strip() for i in row.find_all("td")]

if individual_data:

table_row_data.append(individual_data)

df = pd.DataFrame(table_row_data, columns=column_headers)

df.to_csv("academy_awards.csv", index=False)

#Create a folder for the movies

output_dir = "movies"

if not os.path.exists(output_dir):

os.makedirs(output_dir)

#Find the links to each movie

links = []

for row in table_data.find_all("tr"):

cells = row.find_all("td")

if cells:

link = cells[0].find("a", href=True)

if link:

links.append(urljoin(resp.url, link["href"]))

links = list(dict.fromkeys(links))

print("Number of movie links: ", len(links))

#download each movie's Wikipedia page

for index, url in enumerate(links):

name = url.split("/")[-1]

try:

print("Getting movie: ", name)

response = requests.get(url, headers=headers, timeout=30)

if response.status_code == 200:

with open("movies/" + name + ".html", "w", encoding="utf-8") as f:

f.write(response.text)

else:

print("Failed to download: ", url, response.status_code)

time.sleep(5)

except requests.exceptions.RequestException as e:

print("A network error occured:", e)

6 Upvotes

3 comments sorted by

8

u/sausix 2d ago
  1. Screenshots of code are annoying. Don't think people always can spot bugs directly by reading. Some people may try tonrun your code but they don't wanna type your code first.
  2. Wikipedia data is officially downloadable. If you just wanna learn or just scrape a few pages only then it's fine.
  3. Debug your code. Run step by step, view or track variables. Because you have to learn debugging anyway and you learn the most when you hunt your own bugs.
  4. "Something does not work in my (huge) code" is a bad way to ask for help. Error messages are the key and should not be ignored. Even cryptical error messages are very helpful.

So please explain what exactly is happening or not. Do some basic debugging yourself. Even using print markers to follow execution is fine. Without own effort people get usually less or lousier help.

3

u/baubleglue 2d ago

You need to split the code into meaningful blocks (functions) and hide all the ugly parts in them. By ugly I mean searching specific tags and tables.

def find_award_table(html_text):
    ...
    return table 

You should look into more reliable attributes, like id instead of searching substrings in the text, now your code works only on that specific page. If you make functions like: table_to_dataframe, describe_table. You can use them as library for any next project.

2

u/baubleglue 2d ago

Use logging instead of print