Disclaimer: This is a user generated content submitted by a member of the WriteUpCafe Community. The views and writings here reflect that of the author and not of WriteUpCafe. If you have any complaints regarding this post kindly report it to us.

Initially, you will need a file named Tracker_PRODUCTS.csv with the links for the products you wish to check. After executing the run, the scraper will save the results in a different file known as “search_history_[date].xlsx. These are the files placed inside the search_history folder.

For completing this task, we will require BeautifulSoup as our web scraping tool. If you need to install any of them, a simple script that includes a simple pip/conda install will do. There are various sources that will help, but usually, Python package Index will have it.

Code

import requests
from glob import glob
from bs4 import BeautifulSoup
import pandas as pd
from datetime import datetime
from time import sleep
# http://www.networkinghowtos.com/howto/common-user-agent-list/
HEADERS = ({‘User-Agent':
            ‘Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36',
            ‘Accept-Language': ‘en-US, en;q=0.5'})
# imports a csv file with the url's to scrape
prod_tracker = pd.read_csv(‘trackers/TRACKER_PRODUCTS.csv', sep=';')
prod_tracker_URLS = prod_tracker.url
# fetch the url
page = requests.get(prod_tracker_URLS[0], headers=HEADERS)
# create the object that will contain all the info in the url
soup = BeautifulSoup(page.content, features=”lxml”)

The HEADERS variables need to pass along the get method. Once the file is passed, it might be a good time to get the CSV file known as TRACKER_PRODUCTS.csv from the repository and place it in the folder named “trackers.”

Then, we will execute this through BeautifulSoup. This will convert the HTML into some more convenient file named soup.

If ever you will find soup.find, it will mean that we are in search of an element of the page that uses its HTML tag(such as div, or span, etc.) With soup.select we will use CSS selectors.

# product title
title = soup.find(id='productTitle').get_text().strip()
# to prevent script from crashing when there isn't a price for the product
try:
    price = float(soup.find(id='priceblock_ourprice').get_text().replace(‘.', ”).replace(‘€', ”).replace(‘,', ‘.').strip())
except:
    price = ”
# review score
review_score = float(soup.select(‘.a-star-4-5')[0].get_text().split(‘ ‘)[0].replace(“,”, “.”))
# how many reviews
review_count = int(soup.select(‘#acrCustomerReviewText')[0].get_text().split(‘ ‘)[0].replace(“.”, “”))
# checking if there is “Out of stock” and if not, it means the product is available
try:
    soup.select(‘#availability .a-color-state')[0].get_text().strip()
    stock = ‘Out of Stock'
except:
    stock = ‘Available'

(De)constructing the soup

There is also a script for getting prices in USD is added

screenshot

Once the testing is completed, the proper script is to be written which will:

  • Fetch the URLs from a CSV file.
  • Will use a while loop to scrape every product and save the information.
  • Save all the results that will include previous searches in an excel file.

You will also need a scraper, and we will call it Amazon_scraper.py.

For Code Click Here: https://www.3idatascraping.com/how-to-scrape-amazon-stores-for-generating-price-alerts.php

Tracker Products

Observations on the file TRACKER_PRODUCTS.csv It's a simple file only with three columns (“link,” “code,” and “buy below”). That's where you'll enter the product URLs you'd like to track.

You may even put this file in a synced Dropbox folder (and then update the script with the updated file URLs) so that you really can update it from your phone at any time. If you execute the script on a server or on your personal laptop at home, it will pick up that new product link from the file in its next run.

Search History

The SEARCH HISTORY files are the same way. On the very first run, you must add an empty file to both the folder “search history” (which may be found in the repository). When establishing the last search variable on line 116 of the script above, we're looking for the most recent file in the search history folder. As a result, you must additionally put your own directory here. Simply change the text with the name of the folder where you'll be working on this project (in my case, “Amazon Scraper“).

Price Alert

Line 97 of the script above contains a section that you may use to send an email with an alert if the price falls below your limit. The reason it's inside a try command is that we don't always get a real price from the product page, so the logical comparison would fail – for example, if the product was unavailable.

Setting up a Scheduled Task for Running Script

Setting up an automated task for executing small scripts.

1. You will initiate it by opening “Task Scheduler”. Then select “Create Task” and pick up the “triggers” tab.

screenshot

2. Next, you will need to move to the Actions tab. Here, you will need to add an action and pick your Python folder location for the “Program/script” box.

3. In the arguments box, you will need to type the name of our file with the function

4. We will tell the system to start the command in the folder where our file Amazon_Scraper.py is.

screenshot

After running this script, the task is ready to run.

For any queries related to scraping Amazon stores for generating price alerts, contact 3i Data Scraping.

https://www.3idatascraping.com/
Do you like 3i Data Scraping's articles? Follow on social!

Login

Welcome to WriteUpCafe Community

Join our community to engage with fellow bloggers and increase the visibility of your blog.
Join WriteUpCafe