爬虫 | 网页更新时邮件提醒(新手)

来自一场焦灼的等待

陶玮 写于 2017-07-20

本文针对特定网页,在服务器上定时执行Python脚本获取信息,于网页内容更新时触发邮件提醒。(本文针对初学者,因为我就是刚接触的:P)
PS:代码在最后:)

1. 【抓内容】明确网页中要抓取的内容,采用Beautiful Soup(Python爬虫利器)库进行抓取
举例:通过浏览器的开发者工具,选中要抓取的部分,获得其标签,如下图,其标签为div.post-content-preview,后续可以使用soup.select(div.post-content-preview)
网页标签查看
参考 | python爬虫:BeautifulSoup 使用select方法详解

2. 【作比较】利用filecmp库函数将更新前的文件与当前抓取的文件进行比较
举例:比较的两个文件为old.txtnew.txt

1
2
3
4
5
r = filecmp.cmp(r'old.txt',r'new.txt') #两个文件的比较结果
if(r == True): #两个文件相同
...
else: #两个文件不同
...

Reference | filecmp — File and Directory Comparisons
参考 | python—filecmp

3. 【发通知】用SMTP发送邮件
我用的是第三方SMTP服务,下面的参考内容详细且清晰,故不赘述。
参考 | Python SMTP发送邮件

4. 【定时抓】Linux服务器上添加定时执行Python脚本
参考 | Linux Crontab 定时任务

5. 【何缘故】做这个的缘由
因为……我在等苹果暑期教育优惠……但是中国区一直没出来……我就很焦急……但又不想频繁地去刷新查看,影响工作效率,所以,做了这样一个非常粗糙简单的网页更新邮件提醒:P
核心代码部分如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# coding: utf8
import re
import requests
import filecmp
import os
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

header = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36',
'Referer': 'http://www.bing.com/',
}

requests.packages.urllib3.disable_warnings()

def process(p):
url = 'http://www.apple.com/cn-k12/shop' # 抓取的网页地址
r = requests.get(url, headers=header, timeout=12999, verify=False)
r.encoding = "utf-8" # 抓取的网页编码

soup = BeautifulSoup(r.text, "lxml")
titles = soup.select('div#page') # 抓取的内容标签
res = []
for title in titles[:min(5, len(titles))]:
res.append(' '.join(title.get_text().split()))
return res
if __name__ == '__main__':
r = filecmp.cmp(r'old.txt',r'new.txt')
if(r == True):
print ':(还木有更新'
else:
# 第三方SMTP服务
mail_host="smtp.exmail.qq.com" # 设置服务器(此处为腾讯企业邮箱)
mail_user="admin@itaowei.cn" # 邮箱地址
mail_pass="mimaxiezaizheli" # 密码

sender = 'admin@itaowei.cn'
receivers = ['taowei86@163.com'] # 接收邮箱地址
# 3个参数:第1个为文本内容,第2个plain设置文本格式,第3个utf-8设置编码
message = MIMEText('苹果教育商店更新啦!', 'plain', 'utf-8')
message['From'] = Header("itaowei.cn", 'utf-8')
message['To'] = Header("更新啦!", 'utf-8')
subject = '苹果教育商店更新啦!'
message['Subject'] = Header(subject, 'utf-8')

try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25) # 25为SMTP端口号
smtpObj.login(mail_user,mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
print "邮件发送成功XD"
except smtplib.SMTPException:
print "Error: 无法发送邮件T_T"


我要是哪里没说清楚,欢迎留言讨论:)
PS:如需引用,还望注明出处。


分享至: 微博 微信 空间 QQ



* 提示 | 本网站评论系统自2017年5月7日由多说更换为畅言。因迁移数据表情/头像显示错误,故未予显示,尽请谅解。