本人小白一枚,简单记录下学校作业项目,代码十分简单,主要是对各个库的理解,希望能给别的初学者一点启发。O(∩_∩)O
python定时简单爬取网页新闻存入数据库并发送邮件
一、项目要求
1、程序可以从北京工业大学首页上爬取新闻内容:http://www.bjut.edu.cn
2、程序可以将爬取下来的数据写入本地MySQL数据库中。
3、程序可以将爬取下来的数据发送到邮箱。
4、程序可以定时执行。
二、项目分析
1、爬虫部分利用requests库爬取html文本,再利用bs4中的BeaultifulSoup库来解析html文本,提取需要的内容。
2、使用pymysql库连接MySQL数据库,实现建表和插入内容操作。
3、使用smtplib库建立邮箱连接,再使用email库将文本信息加工成邮件消息并发送。
4、使用schedule库实现定时执行该程序。
三、代码分析
1、导入需要的库:
import requests
from bs4 import BeautifulSoup
import pymysql
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import time
import schedule
2、获取html文件:
def getHTMLtext(url):
try:
headers={
"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36",
}
r = requests.get(url, headers = headers, timeout = 30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
其中必须添加请求头headers否则get请求时会返回错误页面。
raise_for_status()可以根据状态码判断连接对象的状态,如果成功便继续执行,若连接失败则抛出异常,因此利用try-except捕获。
apparent_encoding()方法可以解析判断可能的编码方式。
3、解析html提取数据:
首先观察网页源码确定新闻标签位置:
def parseHTML(
news, html):
soup = BeautifulSoup(html, "html.parser")
for i in soup.find(attrs = {'class' : 'list'}).find_all('li'):
date = i.p.string + '-' + i.h2.string
href = i.a['href']
title = i.find('h1').string
content = i.find_all('p')[1].string
news.append([date, href, title, content])
4、存入数据库
def toMysql(news):
conn = pymysql.connect(host = 'localhost', port = 3306, user = 'root', passwd = '数据库密码', db = '数据库名称',charset = 'gbk', connect_timeout = 1000)
cursor = conn.cursor()
sql = '''
create table if not exists tb_news(
日期 date,
链接 varchar(400),
标题 varchar(400),
梗概 varchar(400))
'''
cursor.execute(sql)
for new in news:
sql = 'insert into tb_news(日期, 链接, 标题, 梗概) values(%s, %s, %s, %s)'
date = new[0]
href = new[1]
title = new[2]
content = new[3]
cursor.execute(sql, (date, href, title, content))
conn.commit()
conn.close()
- 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
- 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
-
由于新闻字数较多,存取时可能会有乱码以及数据过长存储失败的问题,与数据库编码有关,可以在MySQL的my.ini配置文件中修改默认编码为gbk。
5、发送邮件
def sendMail(news):
from_addr = '发送邮箱'
password = '16位授权码'
to_addr = '接收邮箱'
mailhost = 'smtp.qq.com'
qqmail = smtplib.SMTP()
qqmail.connect(mailhost, 25)
qqmail.login(from_addr, password)
content = ''
for new in news:
content += '新闻时间:' + new[0] + '\n' + '新闻链接:' + new[1] + '\n' + '新闻标题:' + new[2] + '\n' + '新闻梗概:' + new[3] + '\n'
content += '======================================================================\n'
subject = time.strftime('%Y-%m-%d %X', time.localtime(time.time())) + '时爬取的北工大首页主要新闻\n'
msg = MIMEText(content, 'plain', 'utf-8')
msg['subject'] = Header(subject, 'utf-8')
try:
qqmail.sendmail(from_addr, to_addr, msg.as_string())
print('发送成功')
except:
print('发送失败')
qqmail.quit()
- 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
- 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
-
注意其中的密码不是指邮箱的登录密码,而是指邮箱的smtp授权码,qq邮箱可以再设置中开启smtp服务,并获取授权码。
6、主函数
def main():
news = []
url = "http://www.bjut.edu.cn/"
html = getHTMLtext(url)
parseHTML(news, html)
toMysql(news)
print(news)
sendMail(news)
-
输入北京工业大学官网的url并新建一个列表news用来存放消息,然后依次调用函数爬取新闻存入数据库并发到邮箱。为了检验上述程序是否可以完成任务,先调用依次main()函数并print(news)看看结果:
main()
结果如下:
由此可见程序执行正常。
7、定时执行
schedule.every().monday.at("08:00").do(main)
while True:
schedule.run_pending()
time.sleep(1)
用死循环保证schedule一直运行。设定的是每周一早上8:00执行程序。
为了方便检查效果,先将运行时间改为每5s运行一次:
schedule.every(5).seconds.do(main)
每5s便可以收到一封邮件,由此可见满足定时需求。至此程序结束。
四、完整代码
import requests
from bs4 import BeautifulSoup
import pymysql
import smtplib
from email.mime.text import MIMEText
from email.header import Header
import time
import schedule
def getHTMLtext(url):
try:
headers={
"user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36",
}
r = requests.get(url, headers = headers, timeout = 30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""
def parseHTML(news, html):
soup = BeautifulSoup
(html, "html.parser")
for i in soup.find(attrs = {'class' : 'list'}).find_all('li'):
date = i.p.string + '-' + i.h2.string
href = i.a['href']
title = i.find('h1').string
content = i.find_all('p')[1].string
news.append([date, href, title, content])
def toMysql(news):
conn = pymysql.connect(host = 'localhost', port = 3306, user = 'root', passwd = '数据库密码', db = '数据库名称',charset = 'gbk', connect_timeout = 1000)
cursor = conn.cursor()
sql = '''
create table if not exists tb_news(
日期 date,
链接 varchar(400),
标题 varchar(400),
梗概 varchar(400))
'''
cursor.execute(sql)
for new in news:
sql = 'insert into tb_news(日期, 链接, 标题, 梗概) values(%s, %s, %s, %s)'
date = new[0]
href = new[1]
title = new[2]
content = new[3]
cursor.execute(sql, (date, href, title, content))
conn.commit()
conn.close()
def sendMail(news):
from_addr = '发送邮箱'
password = '16位授权码'
to_addr = '接收邮箱'
mailhost = 'smtp.qq.com'
qqmail = smtplib.SMTP()
qqmail.connect(mailhost, 25)
qqmail.login(from_addr, password)
content = ''
for new in news:
content += '新闻时间:' + new[0] + '\n' + '新闻链接:' + new[1] + '\n' + '新闻标题:' + new[2] + '\n' + '新闻梗概:' + new[3] + '\n'
content += '======================================================================\n'
subject = time.strftime('%Y-%m-%d %X', time.localtime(time.time(
))) + '时爬取的北工大首页主要新闻\n'
msg = MIMEText(content, 'plain', 'utf-8')
msg['subject'] = Header(subject, 'utf-8')
try:
qqmail.sendmail(from_addr, to_addr, msg.as_string())
print('发送成功')
except:
print('发送失败')
qqmail.quit()
def main():
news = []
url = "http://www.bjut.edu.cn/"
html = getHTMLtext(url)
parseHTML(news, html)
print(news)
sendMail(news)
schedule.every().monday.at("08:00").do(main)
while True:
schedule.run_pending()
time.sleep(1)
- 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
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 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
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111