首页 > python爬虫

python爬虫今日热榜数据到txt文件的源码

时间:2021-03-27 python爬虫 查看: 771

今日热榜:https://tophub.today/

爬取数据及保存格式:

爬取后保存为.txt文件:

部分内容:


源码及注释:

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  标题:{} \n  热度:{}\n  链接:{}\n  ------------\n"""
  output2 = """平台:{}  榜单类型:{}  最近更新:{}\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() # 获取平台名字
    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() # 获取类型 
    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():
  #   综合  科技  娱乐  社区    购物   财经
  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()

到此这篇关于python爬虫今日热榜数据到txt文件的源码的文章就介绍到这了,更多相关python爬虫今日热榜数据内容请搜索python博客以前的文章或继续浏览下面的相关文章希望大家以后多多支持python博客!

展开全文
上一篇:Python爬虫实例之2021猫眼票房字体加密反爬策略(粗略版)
下一篇:Python爬虫+tkinter界面实现历史天气查询的思路详解
输入字:
相关知识
Python爬虫基础之爬虫的分类知识总结

来给大家讲python爬虫的基础啦,首先我们从爬虫的分类开始讲起,下文有非常详细的知识总结,对正在学习python的小伙伴们很有帮助,需要的朋友可以参考下

Python爬虫基础讲解之请求

今天带大家了解一下python爬虫的基础知识,文中有非常详细的解释说明,对正在学习python爬虫的小伙伴们有很好地帮助,需要的朋友可以参考下

PyQt5爬取12306车票信息程序的实现

12306是学习爬虫的比较好的一个练手网站。本文主要实现了PyQt5爬取12306车票信息程序,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

Python爬虫之m3u8文件里提取小视频的正确姿势

本文给大家分享如何正确提取m3u8文件里的.ts视频,并合成完整的.mp4格式视频,通过图文实例代码的形式给大家介绍的非常详细,对Python提取m3u8文件小视频感兴趣的朋友一起看看吧