Checking Amazon Product Availability Using Python

| | | | | |

👻 Check our latest review to choose the best laptop for Machine Learning engineers and Deep learning tasks!

As we know, Python is a multipurpose language widely used for scripting. Its use is not limited only to solving complex calculations, but also to automating everyday tasks. Let’s say we want to track the availability of any Amazon product and close a deal when the product’s availability changes, as well as inform the user of the availability by email. It will be a lot of fun to write a Python script for this. Note. Install the required libraries (according to the code) before running the script. Also note that if the product is not currently available, no email will be sent to the user. The Asin Id must be provided by the user for the product they want to track.

Working of each module used:
  • -> requests: Used to make HTTP get and post requests
  • -> time: Used to find current time, wait, sleep
  • -> schedule: Used to schedule a function to run again after intervals. It is similiar to "setInterval‚" functionality in JavaScript.
  • -> smptlib: Used to send email using Python.

# Python script for Amazon product availability checker
# importing libraries
from lxml import html
import requests
from time import sleep
import time
import schedule
import smtplib

# Email id for who want to check availability
receiver_email_id = "EMAIL_ID_OF_USER"


def check(url):
	headers = {’User-Agent’: ’Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36’}
	
	# adding headers to show that you are
	# a browser who is sending GET request
	page = requests.get(url, headers = headers)
	for i in range(20):
		# because continuous checks in
		# milliseconds or few seconds
		# blocks your request
		sleep(3)
		
		# parsing the html content
		doc = html.fromstring(page.content)
		
		# checking availaility
		XPATH_AVAILABILITY = ’//div[@id ="availability"]//text()’
		RAw_AVAILABILITY = doc.xpath(XPATH_AVAILABILITY)
		AVAILABILITY = ’’.join(RAw_AVAILABILITY).strip() if RAw_AVAILABILITY else None
		return AVAILABILITY

	
def sendemail(ans, product):
	GMAIL_USERNAME = "YOUR_GMAIL_ID"
	GMAIL_PASSWORD = "YOUR_GMAIL_PASSWORD"
	
	recipient = receiver_email_id
	body_of_email = ans
	email_subject = product + ’ product availability’
	
	# creates SMTP session
	s = smtplib.SMTP(’smtp.gmail.com’, 587)
	
	# start TLS for security
	s.starttls()
	
	# Authentication
	s.login(GMAIL_USERNAME, GMAIL_PASSWORD)
	
	# message to be sent
	headers = "
".join(["from: " + GMAIL_USERNAME,
						"subject: " + email_subject,
						"to: " + recipient,
						"mime-version: 1.0",
						"content-type: text/html"])

	content = headers + "

" + body_of_email
	s.sendmail(GMAIL_USERNAME, recipient, content)
	s.quit()


def ReadAsin():
	# Asin Id is the product Id which
	# needs to be provided by the user
	Asin = ’B077PWK5BT’
	url = "http://www.amazon.in/dp/" + Asin
	print ("Processing: "+url)
	ans = check(url)
	arr = [
		’Only 1 left in stock.’,
		’Only 2 left in stock.’,
		’In stock.’]
	print(ans)
	if ans in arr:
		# sending email to user if
		# in case product available
		sendemail(ans, Asin)

# scheduling same code to run multiple
# times after every 1 minute
def job():
	print("Tracking....")
	ReadAsin()

schedule.every(1).minutes.do(job)

while True:
	
	# running all pending tasks/jobs
	schedule.run_pending()
	time.sleep(1)

Output:

Tracking....
Processing: http://www.amazon.in/dp/B077PWK5BT
Only 1 left in stock.
Tracking....
Processing: http://www.amazon.in/dp/B077PWK5BT
Only 1 left in stock.
Tracking....
Processing: http://www.amazon.in/dp/B077PWK5BT
Only 1 left in stock.

How to create a stock availability checker with python requests if JavaScript is used?

StackOverflow question

I wrote some code which should check whether a product is back in stock and when it is, send me an email to notify me. This works when the things I’m looking for are in the html.

However, sometimes certain objects are loaded through JavaScript. How could I edit my code so that the web scraping also works with JavaScript?

This is my code thus far:

import time
import requests

while True:
    # Get the url of the IKEA page
    url = ’https://www.ikea.com/nl/nl/p/flintan-bureaustoel-vissle-zwart-20336841/’

    # Get the text from that page and put everything in lower cases
    productpage = requests.get(url).text.lower()

    # Set the strings that should be on the page if the product is not available
    outofstockstrings = [’niet beschikbaar voor levering’, ’alleen beschikbaar in de winkel’]

    # Check whether the strings are in the text of the webpage
    if any(x in productpage for x in outofstockstrings):
        time.sleep(1800)
        continue
    else:
        # send me an email and break the loop

Answer:

Instead of scraping and analyzing the HTML you could use the inofficial stock API that the IKEA website is using too. That API return JSON data which is way easier to analyze and you’ll also get estimates when the product gets back to stock.

There even is a project written in javascript / node which provides you this kind of information straight from the command line: https://github.com/Ephigenia/ikea-availability-checker

You can easily check the stock amount of the chair in all stores in the Netherlands:

npx ikea-availability-checker stock --country nl 20336841

👻 Read also: what is the best laptop for engineering students?

Checking Amazon Product Availability Using Python __del__: Questions

How can I make a time delay in Python?

5 answers

I would like to know how to put a time delay in a Python script.

2973

Answer #1

import time
time.sleep(5)   # Delays for 5 seconds. You can also use a float value.

Here is another example where something is run approximately once a minute:

import time
while True:
    print("This prints once a minute.")
    time.sleep(60) # Delay for 1 minute (60 seconds).

2973

Answer #2

You can use the sleep() function in the time module. It can take a float argument for sub-second resolution.

from time import sleep
sleep(0.1) # Time in seconds

Checking Amazon Product Availability Using Python __del__: Questions

How to delete a file or folder in Python?

5 answers

How do I delete a file or folder in Python?

2639

Answer #1


Path objects from the Python 3.4+ pathlib module also expose these instance methods:

How do I copy a string to the clipboard?

2 answers

Dancrew32 By Dancrew32

I"m trying to make a basic Windows application that builds a string out of user input and then adds it to the clipboard. How do I copy a string to the clipboard using Python?

215

Answer #1

Actually, pywin32 and ctypes seem to be an overkill for this simple task. Tkinter is a cross-platform GUI framework, which ships with Python by default and has clipboard accessing methods along with other cool stuff.

If all you need is to put some text to system clipboard, this will do it:

from Tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append("i can has clipboardz?")
r.update() # now it stays on the clipboard after the window is closed
r.destroy()

And that"s all, no need to mess around with platform-specific third-party libraries.

If you are using Python 3, replace TKinter with tkinter.

Python script to copy text to clipboard

2 answers

I just need a python script that copies text to the clipboard.

After the script gets executed i need the output of the text to be pasted to another source. Is it possible to write a python script that does this job?

194

Answer #1

See Pyperclip. Example (taken from Pyperclip site):

import pyperclip
pyperclip.copy("The text to be copied to the clipboard.")
spam = pyperclip.paste()

Also, see Xerox. But it appears to have more dependencies.

We hope this article has helped you to resolve the problem. Apart from Checking Amazon Product Availability Using Python, check other __del__-related topics.

Want to excel in Python? See our review of the best Python online courses 2022. If you are interested in Data Science, check also how to learn programming in R.

By the way, this material is also available in other languages:



Julia Nickolson

Abu Dhabi | 2022-12-07

Maybe there are another answers? What Checking Amazon Product Availability Using Python exactly means?. Will use it in my bachelor thesis

Anna Zelotti

Rome | 2022-12-07

__del__ is always a bit confusing 😭 Checking Amazon Product Availability Using Python is not the only problem I encountered. I am just not quite sure it is the best method

Jan Schteiner

Berlin | 2022-12-07

I was preparing for my coding interview, thanks for clarifying this - Checking Amazon Product Availability Using Python in Python is not the simplest one. I just hope that will not emerge anymore

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically