
今日熱榜:https://tophub.today/爬取數(shù)據(jù)及保存格式:爬取后保存為.txt文件
今日熱榜:https://tophub.today/

爬取數(shù)據(jù)及保存格式:

爬取后保存為.txt文件:

部分內(nèi)容:


源碼及注釋?zhuān)?/p>
import?requests
from?bs4?import?BeautifulSoup
?
def?download_page(url):
headers?=?{"User-Agent":?"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"}
try:
r?=?requests.get(url,timeout?=?30,headers=headers)
return?r.text
except:
return?"please inspect your url or setup"
?
?
def?get_content(html,tag):
output?=?""" 排名:{}\n 標(biāo)題:{} \n 熱度:{}\n 鏈接:{}\n ------------\n"""
output2?=?"""平臺(tái):{} 榜單類(lèi)型:{} 最近更新:{}\n------------\n"""
num=[]
title=[]
hot=[]
href=[]
soup?=?BeautifulSoup(html,?'html.parser')
con?=?soup.find('div',attrs={'class':'bc-cc'})
con_list?=?con.find_all('div',?class_="cc-cd")
for?i?in?con_list:
author?=?i.find('div',?class_='cc-cd-lb').get_text()?# 獲取平臺(tái)名字
time?=?i.find('div',?class_='i-h').get_text()?# 獲取最近更新
link?=?i.find('div',?class_='cc-cd-cb-l').find_all('a')?# 獲取所有鏈接
gender?=?i.find('span',?class_='cc-cd-sb-st').get_text()?# 獲取類(lèi)型
save_txt(tag,output2.format(author,?gender,time))
for?k?in?link:
href.append(k['href'])
num.append(k.find('span',?class_='s').get_text())
title.append(str(k.find('span',?class_='t').get_text()))
hot.append(str(k.find('span',?class_='e').get_text()))
for?h?in?range(len(num)):
save_txt(tag,output.format(num[h],?title[h],?hot[h],?href[h]))
?
?
def?save_txt(tag,*args):
for?i?in?args:
with?open(tag+'.txt',?'a',?encoding='utf-8')?as?f:
f.write(i)
?
?
def?main():
# 綜合 科技 娛樂(lè) 社區(qū) 購(gòu)物 財(cái)經(jīng)
page=['news','tech','ent','community','shopping','finance']
for?tag?in?page:
url?=?'https://tophub.today/c/{}'.format(tag)
html?=?download_page(url)
get_content(html,tag)
?
if?__name__?==?'__main__':
main()
到此這篇關(guān)于python爬蟲(chóng)今日熱榜數(shù)據(jù)到txt文件的源碼的文章就介紹到這了!

掃下方二維碼加老師微信
或是搜索老師微信號(hào):XTUOL1988【切記備注:學(xué)習(xí)Python】
領(lǐng)取Python web開(kāi)發(fā),Python爬蟲(chóng),Python數(shù)據(jù)分析,人工智能等學(xué)習(xí)教程。帶你從零基礎(chǔ)系統(tǒng)性的學(xué)好Python!
也可以加老師建的Python技術(shù)學(xué)習(xí)教程qq裙:245345507,二者加一個(gè)就可以!
歡迎大家點(diǎn)贊,留言,轉(zhuǎn)發(fā),轉(zhuǎn)載,感謝大家的相伴與支持
萬(wàn)水千山總是情,點(diǎn)個(gè)【在看】行不行
*聲明:本文于網(wǎng)絡(luò)整理,版權(quán)歸原作者所有,如來(lái)源信息有誤或侵犯權(quán)益,請(qǐng)聯(lián)系我們刪除或授權(quán)事宜