前言
这个项目的第三篇博客,增加了定时爬取和日志写入,解决了一些稳定性的问题。
代码设计
# -*- encoding: utf-8 -*-
# ---------------------------------------------
# 微博热搜
# ---------------------------------------------
import time
import re
import json
import sys
import copy
import pymysql
import requests#引入requests库用于下载网页
from bs4 import BeautifulSoup#BeautifulSoup用于解析网页
localtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())#获取时间
try:
data=requests.get("https://s.weibo.com/top/summary?Refer=top_hot&topnav=1&wvr=6").text#请求网站
except:
print(localtime+'\t'+"爬取失败!")
soup=BeautifulSoup(data,'html.parser')#使用BeautifulSoup工具
a=[]#创建一个空列表
index=[]
try:
db = pymysql.connect("xxx.xxx.xxx.xxx", "xxx", "xxx", "xxx", use_unicode=1,charset='utf8' )
cursor = db.cursor()
except:
print(localtime+'\t'+"打开数据库失败!")
try:
for k in soup.find_all('a',attrs={'href':re.compile('^/weibo?'),'target' : '_blank'}): #把热度标题添加进空列表
sql = """INSERT INTO hot_date(NAME, URL, TIME) VALUES ("%s",'%s','%s')""" % (str(k.get_text().strip()),"https://s.weibo.com"+k.get('href'),localtime)
try:
cursor.execute(sql)
db.commit()
except:
flag=1
db.close()
print(localtime+'\t'+"存入成功!")
except:
print(localtime+'\t'+"存入失败!")
说明
运行在linux上,用Crontab设置定时任务。教程
通过输出重定向写入日志文件
问题解决
1.运行错误
遇到了requests不能用的问题,在安装了requests库的情况下Linux无法运行
解决方法:增加try异常机制
2.Crontab运行错误
设置时使用绝对路径
后记
接下来就是记录结束时间和持续时间