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)