python爬取微博熱搜


 功能

利用python爬取新浪微博熱搜,並設置為定時任務,每天定時自動運行。

源代碼

 1 import requests
 2 import re
 3 import bs4
 4 import os
 5 import datetime
 6 
 7 url="https://s.weibo.com/top/summary"
 8 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"}
 9 try:
10     r=requests.get(url,headers=headers)
11 except:
12     print("出現了不可預期的錯誤")
13 
14 hotPattern=re.compile('(<tr class="">[\s,\S]*?</tr>)')
15 hotList=re.findall(hotPattern,r.text)
16 if hotList==[]:
17     print("匹配模式可能出了問題")
18 else:
19     #接下來開始提取熱搜數據
20     dataList=[]
21     for hotPoint in hotList:
22         data=[]
23         hotSoup=bs4.BeautifulSoup(hotPoint,'html.parser')
24         #獲取排名
25         #print(hotSoup.tr.contents[1])
26         rank=hotSoup.tr.contents[1].string
27         if rank==None:
28             data.append("速升")
29         else:
30             data.append(rank)
31         
32         #獲取熱搜名稱
33         #print(hotSoup.tr.contents[3])
34         name=hotSoup.tr.contents[3].a.string
35         data.append(name)
36             
37         dataList.append(data)
38 
39     #創建文件夾
40     cwd=os.getcwd()
41     time=datetime.datetime.now().strftime(r'%Y\%m')   #以【年/月/】作為目錄
42     day=datetime.datetime.now().strftime(r'\%d')      #以【日.txt】作為文件名
43     file=cwd+'\\'+time
44     if not(os.path.exists(file)):
45         os.makedirs(file)
46     with open(file+day+'.txt','w') as f:
47         for data in dataList:
48             tmp=""
49             for da in data:
50                 tmp+=da.ljust(10)
51             tmp+='\n'
52             f.write(tmp)
53     
54     
55         

設置定時任務

打開控制面板——》選擇系統和安全——》選擇管理工具——》打開任務計划程序

 

 

選擇創建任務

設置基本屬性

 

設置觸發器

 

設置操作(注意要設置起始位置為文件所在目錄)

 

設置條件

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM