需求是,当有新品发布时,能立即收到邮件提醒。因为抢单的人很少,所以只需要完成提醒就行。
思路就是,利用python的requests库间隔10秒去获取下网页内容,检测商品列表中第一个商品的商品编号是否改变,如果改变就说明是新品,需要发送邮件。
封装了下worker类,主要函数在check中:
-
import requests
-
import traceback
-
import time
-
from bs4
import BeautifulSoup
-
import logging
-
from send_email
import SendMail
-
logging.basicConfig(filename=
'watch.log', level=logging.WARNING,
-
format=
'%(asctime)s %(filename)s[line:%(lineno)d] %(message)s', datefmt=
'%a, %d %b %Y %H:%M:%S')
-
-
class Worker():
-
def __init__(self,start):
-
self.start=start
-
self.firstStart=
True
-
-
def check(self):
-
logging.warning(
"old:"+self.start)
-
s=requests.Session()
-
ret=s.get(
"http://matenrow.net/17.html")
-
soup_string = BeautifulSoup(ret.content,
"html.parser")
-
book_a = soup_string.findAll(attrs={
"class":
"M9_1_font_other"})
-
book=book_a[
0]
-
if book.string!=self.start:
-
self.start=book.string
-
logging.warning(
"old:{},new:{}".format(self.start,book.string))
-
return
True
-
else:
-
return
False
接下来就是放到一个循环中,sleep10秒去执行下:
-
if __name__ ==
'__main__':
-
worker=Worker(
"G1960")
-
while
True:
-
try:
-
ret=worker.check()
-
logging.warning(ret)
-
if worker.firstStart:
-
worker.firstStart=
False
-
continue
-
if ret:
-
SendMail(
"xxxx@qq.com",
"提醒新产品",
"标号:{}".format(worker.start))
-
except Exception
as e:
-
logging.warning(
"err:{},trace:{}".format(str(e),traceback.format_exc()))
-
time.sleep(
10)
发送邮件SendMail的代码, 可参考这篇博客。
原文:一只小coder
连接:https://blog.csdn.net/u014633966/article/details/86073961