|
| 1 | +import requests |
| 2 | +from bs4 import BeautifulSoup |
| 3 | + |
| 4 | +def scrape_amazon_bestsellers(category_url): |
| 5 | + headers = { |
| 6 | + "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"} |
| 7 | + response = requests.get(category_url, headers=headers) |
| 8 | + |
| 9 | + if response.status_code == 200: |
| 10 | + soup = BeautifulSoup(response.content, 'html.parser') |
| 11 | + products = soup.find_all('div', class_='zg-item-immersion') |
| 12 | + |
| 13 | + for index, product in enumerate(products, start=1): |
| 14 | + title = product.find('div', class_='p13n-sc-truncate').get_text().strip() |
| 15 | + rank = index |
| 16 | + print(f"Rank: {rank}\nTitle: {title}\n") |
| 17 | + |
| 18 | + else: |
| 19 | + print("Failed to retrieve data from Amazon.") |
| 20 | + |
| 21 | +if __name__ == "__main__": |
| 22 | + category_url = "https://www.amazon.com/Best-Sellers-Electronics/zgbs/electronics/" |
| 23 | + scrape_amazon_bestsellers(category_url) |
0 commit comments