抓取网页新闻(各个_encoding(_status)O_O完整代码分析 )
优采云 发布时间: 2022-01-14 18:07抓取网页新闻(各个_encoding(_status)O_O完整代码分析
)
我是新手,简单记录学校的作业项目。代码很简单,主要是我对各个库的理解,希望能给其他初学者一些启发。O(∩_∩)O
Python 定期抓取网络新闻并将其存储在数据库中并发送电子邮件
一、项目要求
1、程序可以抓取北京工业大学主页的新闻内容:
2、程序可以将爬取的数据写入本地MySQL数据库。
3、程序可以将爬取的数据发送到邮箱。
4、程序可以定期执行。
二、项目分析
1、爬虫部分使用requests库爬取html文本,然后使用bs4中的BeautifulSoup库解析html文本提取需要的内容。
2、使用pymysql库连接MySQL数据库,创建表和插入内容。
3、使用smtplib库建立邮箱连接,然后使用email库将文本信息处理成邮件发送出去。
4、使用调度库定时执行程序。
三、代码分析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文件:
# 连接获取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 ""
必须添加请求头标头,否则在获取请求时会返回错误页面。
raise_for_status() 可以根据状态码判断连接对象的状态。如果成功,它将继续执行。如果连接失败,会抛出异常,所以被try-except捕获。
visible_encoding() 方法可以解析和确定可能的编码。
3、解析 html 以提取数据:
首先观察网页源代码,确定新闻标签的位置:
# 解析html提取数据
def parseHTML(news, html):
soup = BeautifulSoup(html, "html.parser") # 获取soup
for i in soup.find(attrs = {'class' : 'list'}).find_all('li'): # 存放新闻的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()
5、发送电子邮件
# 发送邮件
def sendMail(news):
from_addr = '发送邮箱' # 发送邮箱
password = '16位授权码' # 邮箱授权码
to_addr = '接收邮箱' # 接收邮箱
mailhost = 'smtp.qq.com' # qq邮箱的smtp地址
qqmail = smtplib.SMTP() # 建立SMTP对象
qqmail.connect(mailhost, 25) # 25为SMTP常用端口
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'
# 加工邮件message格式
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()
6、主函数
# 主函数
def main():
news = []
url = "http://www.bjut.edu.cn/"
html = getHTMLtext(url)
parseHTML(news, html)
toMysql(news)
print(news)
sendMail(news)
main() #测试需要,之后会删除
结果如下:
可以看出程序运行正常。
7、预定执行
# 定时执行整个任务
schedule.every().monday.at("08:00").do(main) # 每周一早上八点执行main函数
while True:
schedule.run_pending()
time.sleep(1)
使用无限循环来确保计划始终运行。设置为每周一上午 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
# 连接获取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 ""
# 解析html提取数据
def parseHTML(news, html):
soup = BeautifulSoup(html, "html.parser") # 获取soup
for i in soup.find(attrs = {'class' : 'list'}).find_all('li'): # 存放新闻的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' # qq邮箱的smtp地址
qqmail = smtplib.SMTP() # 建立SMTP对象
qqmail.connect(mailhost, 25) # 25为SMTP常用端口
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'
# 加工邮件message格式
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) # 每周一早上八点执行main函数
while True:
schedule.run_pending()
time.sleep(1)