python爬取微博热搜
功能
利用python爬取新浪微博热搜,并设置为定时任务,每天定时自动运行。
源代码
import requests
import re
import bs4
import os
import datetime
url="https://s.weibo.com/top/summary"
headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3756.400 QQBrowser/10.5.4039.400"}
try:
r=requests.get(url,headers=headers)
except:
print("出现了不可预期的错误")
hotPattern=re.compile(‘(<tr class="">[\s,\S]*?</tr>)‘)
hotList=re.findall(hotPattern,r.text)
if hotList==[]:
print("匹配模式可能出了问题")
else:
#接下来开始提取热搜数据
dataList=[]
for hotPoint in hotList:
data=[]
hotSoup=bs4.BeautifulSoup(hotPoint,‘html.parser‘)
#获取排名
#print(hotSoup.tr.contents[1])
rank=hotSoup.tr.contents[1].string
if rank==None:
data.append("速升")
else:
data.append(rank)
#获取热搜名称
#print(hotSoup.tr.contents[3])
name=hotSoup.tr.contents[3].a.string
data.append(name)
dataList.append(data)
#创建文件夹
cwd=os.getcwd()
time=datetime.datetime.now().strftime(r‘%Y\%m‘) #以【年/月/】作为目录
day=datetime.datetime.now().strftime(r‘\%d‘) #以【日.txt】作为文件名
file=cwd+‘\\‘+time
if not(os.path.exists(file)):
os.makedirs(file)
with open(file+day+‘.txt‘,‘w‘) as f:
for data in dataList:
tmp=""
for da in data:
tmp+=da.ljust(10)
tmp+=‘\n‘
f.write(tmp)设置定时任务
打开控制面板——》选择系统和安全——》选择管理工具——》打开任务计划程序

选择创建任务
设置基本属性

设置触发器

设置操作(注意要设置起始位置为文件所在目录)

设置条件
