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
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.
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).
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?
Answer #1
os.remove()
removes a file.os.rmdir()
removes an empty directory.shutil.rmtree()
deletes a directory and all its contents.
Path
objects from the Python 3.4+ pathlib
module also expose these instance methods:
pathlib.Path.unlink()
removes a file or symbolic link.pathlib.Path.rmdir()
removes an empty directory.
How do I copy a string to the clipboard?
2 answers
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?
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?