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

1

u/s5EWT Jan 03 '22 edited Jan 03 '22

Reading the docs for `find_all` you are searching for an exact match when you pass it that way. You need to use a css selector to find an element that has multiple classes but not in that exact order.

From the docs https://www.crummy.com/software/BeautifulSoup/bs4/doc/#searching-by-css-class

But searching for variants of the string value won’t work:

css_soup.find_all("p", class_="strikeout body")

If you want to search for tags that match two or more CSS classes, you should use a CSS selector:

css_soup.select("p.strikeout.body")

1

u/creepy_kittycat Jan 03 '22

How can this be the issue if the code was working at the start of running it? (I assume that means when the code started running it was printing full results)

1

u/Hypernova_13 Jan 03 '22

I ran it earlier today and it worked - came back and ran it again, and it had stopped working.

2

u/s5EWT Jan 03 '22

Your find_all is looking for an exact string. All A tags must have a class that matches exactly a-link-normal s-link-style a-text-normal. Looking at the a tags. There are new classes that mess that order up. Amazon can change that order on a whim. Using a CSS selector vs the exact string is more flexible. They also can change the names of the classes anytime they want.

Try

.a-link-normal.s-link-style.a-text-normal

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!

2

u/Hypernova_13 Jan 03 '22

Im fairly certain that it matched up but incase it had changed how would I overcome this?

1

u/creepy_kittycat Jan 03 '22

I haven't found a decent sollution to that, apart from completely changing the strategy and working with Selenium instead of bs4. It's a challenging rabbit hole, I think, but it's not necessarily going to be more reliable. If Amazon has an API, it'd be worth checking into. But in case it doesn't, I don't know what else to say other than keep checking the html (if that's the problem). Although.... I notice in your scrapeResults function you don't have a return statement, but maybe this is by design? In any case, when it comes to scrapers, I'd sleep a night on it and then go back to the problem with fresh eyes and mind :)

1

u/Hypernova_13 Jan 03 '22

I actually had some trouble with accidentally undoing parts of my code so the return statement might have been undone by accident

1

u/creepy_kittycat Jan 04 '22

that's fair, but you still have a print statement so if that's showing to be empty there's still an unrelated issue in there, no?

1

u/SupremeRedditBot Professional Bot || Mod Jan 04 '22

Please Add A Flair To Your Post!

Suggested Flair: [Python]

 


To add a flair:

  • Click flair underneath your post

  • Select a flair

  • Click save

 


I am a bot run by /u/SupremeDesigner for /r/CodingHelp || This was an automated ^response

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.