Sunteți pe pagina 1din 15

What are the best Python scripts you've ever written?

Ah-ha, another interesting question that I love to answer. So, further wasting any time, let's
dive into it.

Chapter 1

THE CONTEXT

Well, first thing first, If you’re an Indian (or any human being), I think you’re familiar with
either one of these:

or…
If so, then congratulations to you. I promise that this code may come very handy to you.
(Don’t worry if you’re not familiar at all, you’ll definitely find this code very interesting).

Now, a bit of myself. I am an average Indian (more specifically, Bengali) with a messy beard,
something just like this:
Now, since Durgapuja ( The biggest festival for Bengali ) is knocking at the door, I badly
need a trimmer to groom myself. Checking various websites for this, I finally stumbled upon
on amazon.

“Ah-ha …. that’s my deal.”, I said to myself. But unfortunately, they haven’t disclosed the
date and price yet. So, the idea came to my mind: It’s better to write a python script such
that when it hits lower than my desired price, I will get a notification mail (or better to
have a push notification) so that the deal is not going to be missed by me.

But before that, let’s see what the current price for the item is?
Hmmm….. 1120. That’s a bit pricy. Anyway, let's dive into chapter 2.

Chapter 2

THE EXECUTION

Let’s fire up the IDLE and type this:

1. #PRICE ALERT FOR AMAZON by SENDING MAIL and PUSH NOTIFICATION


2. #CREATED BY AMLAN SAHA KUNDU
3. #ver 2.1
4.
5. #What's new in version 2.0?
6. # 1. Added push notification features for android.
7. # 2. New formatting in EMAIL SECTION.
8. # 3. Confirmation message after sending MAIL and NOTIFICATION
9.
10. #What's new in version 2.1?
11. # 1. Minor bug fixing
12. # 2. Time stamp added
13. # 3. No. of attempts added
14.
15. #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
16.
17. import requests,time,smtplib
18. from bs4 import BeautifulSoup
19. from notify_run import Notify
20. from datetime import datetime
21.
22. #USER INPUT-------------------------------------but I make it
comment because I want to specify this product only.
23. '''
24. url = input("Enter your URL here : ")
25. dp = int(input("Enter your desired price : "))
26. '''
27. #-----------------------------------------------
28.
29. url = "https://www.amazon.in/Philips-Trimmer-Cordless-QT4001-
15/dp/B00L8PEEAI/ref=sr_1_4?crid=26OVQAIRQLJUU&keywords=philips+qt401
1%2F15&qid=1569507835&s=hpc&sprefix=philips+qt%2Chpc%2C361&sr=1-4"
30. dp = 1000
31. URL = url
32. headers = {"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132
Safari/537.36'}
33.
34.
35. page = requests.get(URL, headers=headers)
36.
37. soup= BeautifulSoup(page.content,'html.parser')
38.
39. #----------------------------------------------------- TO CHECK
WHETHER soup IS WORKING OR NOT
40. '''
41. m=open('soupw.txt',"wb")
42. m.write(soup.prettify().encode("utf-8"))
43. m.close
44. '''
45. #------------------------------------------------------------------
--------------------
46.
47. title = soup.find(id="productTitle").get_text()
48. price = soup.find(id="priceblock_ourprice").get_text()
49. main_price = price[2:]
50.
51. #LETS MAKE IT AN INTEGER-------------------------------------------
--------------------
52.
53. l = len(main_price)
54. if l<=6 :
55. main_price = price[2:5]
56. else:
57. p1 = price[2]
58. p2 = price[4:7]
59. pf = str(p1)+str(p2)
60. main_price = int(pf)
61.
62. price_now = int(main_price)
63.
64. #VARIABLES FOR SENDING MAIL AND PUSH NOTIFICATION------------------
---------------------
65.
66. title1=str(title.strip())
67. main_price1 = main_price
68. pnmsg = "Rs. "+str(main_price1)+" for "+title1
69.
70. print("NAME : "+ title1)
71. print("CURRENT PRICE : "+ str(main_price1))
72. print("DESIRED PRICE : "+ str(dp))
73. #-----------------------------------------------Temporary fixed for
values under Rs. 9,999
74.
75. '''
76. print(title.strip())
77. print(price.strip())
78. print(main_price)
79.
80. print(real_price)
81. print(type(real_price))
82. print(dp)
83. print(type(dp))
84. '''
85. #FUNCTION TO CHECK THE PRICE---------------------------------------
----------------
86.
87.
88. def check_price():
89. count = 0
90. if(price_now <= dp):
91. send_mail()
92. push_notification()
93. else:
94. count = count+1
95. print("Rechecking... Last checked at "+str(datetime.now()))
96.
97. #Lets send the mail------------------------------------------------
-----------------
98.
99. def send_mail():
100. server = smtplib.SMTP('smtp.gmail.com',587)
101. server.ehlo()
102. server.starttls()
103. server.ehlo()
104.
105. server.login('dev.amlan.99@gmail.com','fzanpwfvxnldiycv')
106.
107. subject = "Price of "+title1+" has fallen down to Rs.
"+str(main_price1)
108. body = "Hey Amlan! \n The price of "+title1+" on AMAZON has
fallen down to Rs."+str(main_price1)+", which is less than your
desired price of Rs."+str(dp)+".\n So, hurry up & check the amazon
link right now : "+url
109.
110. msg = f"Subject: {subject} \n\n {body} "
111.
112. server.sendmail(
113. 'dev.amlan.99@gmail.com',
114. 'amlansk53@gmail.com',
115. msg
116. )
117. print("HEY AMLAN, EMAIL HAS BEEN SENT SUCCESSFULLY.")
118.
119.
120. server.quit()
121. #Now let's send the push notification------------------------------
-------------------
122.
123. def push_notification():
124. notify = Notify()
125. notify.send(pnmsg)
126. print("HEY AMLAN, PUSH NOTIFICATION HAS BEEN SENT
SUCCESSFULLY.")
127.
128. print("Check again after an hour.")
129. #Now lets check the price after 1 min -----------------------------
------------------
130. count = 0
131. while(True):
132. count += 1
133. print("Count : "+str(count))
134. check_price()
135. time.sleep(60)

Ooooooo….that looks terrible. Well, let’s see the output first.

So, is it really working?

Let’s check it out.

So, what I did, I just simply change my desired price to 1200 from 1000 in line no. 30 and see
what’s happened:
Meanwhile, my mobile be like…
Voila!….Push Notification works smoothly. But what’s about the email ??

Ah-ha…..that’s my boy. So, my code works. Yuppy :)

Chapter 3

THE EXPLANATION

So, what did I do so far? First I opened my chrome and went to the product webpage. Now
before web-scrapping, I checked whether I can extract information or not. So, I just press F12
and it looked like this:

Pretty messy huh……Nevermind, just turn on the inspect icon from the top left corner like
this:
Ok, so now just hover to the Product name and price tag:

Ok, so the id for the product name is ProductTitle. Now, let's fire up PYTHON IDLE and
write this simple code importing the BeautifulSoup library for web scrapping like this:
Let’s see what we get:

Now, just follow, how we had extracted the title ID of the product and get the ID for the
price. Check whether it’s priceblock_ourprice or not. Now just implement it with our
previous code and print whether it works or not by adding these two lines:

For me, it works perfectly.


Wait, there’s a problem. We get additional ‘₹’ and ‘,’ with our price tag, i.e: “₹ 1,120”. If it
were like 1120, then we would simply convert it to an integer (for further comparison to our
desired price) without any obstacle, like this:

1. price = int(soup.find(id="priceblock_ourprice").get_text())

But, since we have our unexpected guests with us, we would get an error like this:

So, we need a little bit of manipulation. That has been done from line no 51 to 63.
The rest is so simple. I have created an SMTP server for sending emails if the criteria (i.e
amazon_price < = my_desired_price) is met and similarly a push notification sending system
has also been built. Now, the question comes, Will it check the price every time OR only
when I run the code? Now, at the very beginning, as I have mentioned that, I don’t know
when that auspicious time (the time, when the price will be lowest ) will come, I have to run
it until it meets my goal. Thus I construct a while loop from line no. 131 to 135 like this:

1. while(True):
2. count += 1
3. print("Count : "+str(count))
4. check_price()
5. time.sleep(60)

So, it will run after an interval of 60 seconds for the infinite many times :)

Chapter 4

THE Q&As

When I shared this with my friends today, they asked me a few questions that you may ask
me also. Thus I have created this chapter.

 Q. Are you an idiot because you shared the password of your mail?
 A. Well, I may be an idiot, but honestly not for these reasons:

1. I am using Google App password, which is designed especially for a


particular app and it is invalid outside of this app.
2. One requirement for that App Passwords is, I must turn on two-factor
authentication for my mail. So, you don’t trespass my property unless you
have the authentication code, that too valid for 20 seconds.
3. Last but not least, I forget to mention that, I have modified my password ( in
the above code ) from the original app-password provided by google. [ 2 min
silence for those who seemed it real :( ]

 Q. Can I just copy-paste the code to my terminal if I want this to work for me?
 A. First thing first, to run this code, you need to follow the following steps:

1. First, you have to install a few packages like bs4, requests, smtplib, etc. You
can install them via pip easily using pip install <package name>
2. Oh! forget to mention that: this works only in Python 3.x. So, make sure that
you have installed Python 3 and not Python 2.
3. Now, as I have mentioned, I changed my password. So, this server is not going
to be worked for you. You have to create your own server using your
credentials.
4. Lastly, for push notification, you need to register to notify_run after installing
it via pip. You can do that easily typing notify-run register in your
terminal and then scan the QR code to the smartphone in which you want to
send the push notification.

 Q. Does this work for Flipkart?


 A. Sad, but the truth is NO. Flipkart uses dynamic IDs like Quora, so it’s impossible
to track the price because the ID varies from time to time.
 Q. Why did you disclose your mail and letting the people spam you?
 A. Well, to be very frank, I have built a Machine learning model to extract important
mails from the ocean of emails that have flooded my inbox. So, if you’ll send me
more than 3 unnecessary emails ( defined by ML ), then your IP, as well as your
email, will be blacklisted. So, you can give a try so that I can train my model with a
few more datasets :). And, if you want to know how did I make that model, then stay
tuned with me for my future answer. ;)
 Q. Should I contact you if I have any problem performing this code?
 A. Yes, certainly. Just drop a comment or DM me on Quora. I’ll be there for helping
you happily :)

Final Chapter

THE CONCLUSION

S-ar putea să vă placă și