r/CodingHelp • • 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

13 comments sorted by

View all comments

1

u/[deleted] Jan 03 '22

[removed] — view removed comment

1

u/Hypernova_13 Jan 04 '22

Normally I would I was just confused because the program was working, and stopped working despite me not changing a thing

2

u/hollammi Jan 04 '22

You're interacting with somebody else's service. They can and will change their code arbitrarily. It's an inherent problem with web scraping I'm afraid.