r/CodingHelp • u/Hypernova_13 • Jan 03 '22
Python: Amazon web scraper has suddenly stopped working, after changing nothing
I am a 14 year old who is learning python and I am making a simple amazon web scraper to collect the title and price of all the search results (in this case a camera). I am using Beautiful Soup 4 and Requests. After many hours of work, I finished with the work below, which was working. However, after doing something else for a few minutes (unrelated to code), I came back to the program to find it stopped working. Now, the links in the scrapeResults function returned an empty list, despite me not changning anything. This has broken the program, and I cant fix it. Any help would be appreciated.
Code:
from bs4 import BeautifulSoup
from time import sleep
import requests
def makeSoup(url):
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36"}
loop = True
while loop:
try:
page = requests.get(url, headers=headers)
loop = False
except:
print("Connection refused by the server.")
print("Sleeping for 5 seconds...")
sleep(5)
continue
soup = BeautifulSoup(page.content, "lxml")
return soup
def scrapeResults(soup):
links = soup.find_all("a", class_="a-link-normal s-link-style a-text-normal")
print(links)
for link in links:
href = link.get("href")
url = "https://www.amazon.co.uk" + href
s = makeSoup(url)
data = scrapePage(s)
print(data)
def scrapePage(soup):
try:
title = soup.select_one("#productTitle").text.strip()
except:
title = ""
try:
price = soup.find("span", class_="a-offscreen").text.strip()
except:
price = ""
data = {"title": title, "price": price}
return data
def main():
NAME = "camera"
URL = "https://www.amazon.co.uk/s?k=" + NAME
soup = makeSoup(URL)
scrapeResults(soup)
if __name__ == "__main__":
main()
15
Upvotes
1
u/creepy_kittycat Jan 03 '22
Have you checked wehther the html of the target site hasn't changed since you finalised the code last? Some websites use dynamic html tags, meaning the tag and/or class strings change every time you visit the site for example. This would be my first guess. Good luck!