'''爬取知乎热门榜单,提取出排名、链接和问题内容,以日期为文件名格式化存储到本地。'''
from bs4 import BeautifulSoup
from requests_html import HTMLSession
import time
def request_html():
'''爬取返回网页HTML页面'''
url = 'https://tophub.today/n/mproPpoq6O'
session = HTMLSession()
text = session.get(url).text
return text
def parse_html(html_file):
'''解析热榜页面,分类提取每条热榜信息,并存入列表'''
soup = BeautifulSoup(html_file, 'html.parser')
# 查找所有tr,并列成列表
tr_list = soup.select('#page > div.c-d.c-d-e > div.Zd-p-Sc > div:nth-child(1) > div.cc-dc-c > div > div.jc-c '
'> table > tbody > tr')
# 存储爬取信息
rebang = []
# 开始解析信息
for tr in tr_list:
td_lis = tr.find_all('td') #将所有td标签作成列表
xinwen = tr.find('td',class_='al').a #找到有问题的a标签
paiming = td_lis[0].text # 排名
text = xinwen.text #问题内容
lian = xinwen['href'] #链接
redu = td_lis[2].text #热度
lis = [paiming,text,lian,redu] # 第0位是排名,第1位是文字,第2位是链接,第3位是热度
rebang.append(lis)
# 返回解析后信息嵌套列表
return rebang
def format_save(rebang):
'''格式化输出热榜信息'''
ft = time.strftime('%Y-%m-%d',time.gmtime())
with open(ft+'.txt','w') as zhi:
zhi.write('日期:'+ft+'\n')
for i in range(len(rebang)):
this = rebang[i]
header = '排名第' + this[0]
zhi.write('{:-^20}\n'.format(header))
zhi.write('问题:{}\n链接:{}\n热度:{}\n'.format(this[1],this[2],this[3]))
def main():
file = request_html()
rebang = parse_html(file)
format_save(rebang)
main()
练习题:知乎热榜爬取并存储
最新推荐文章于 2021-07-07 16:35:36 发布