Python爬虫在网络上用途广泛,可以用来爬取各种网站的数据。本文将介绍使用Python爬取QQ看点的方法。
import requests
from bs4 import BeautifulSoup
url = 'https://i.match.qq.com/ninja/feeder?site=news&category=news_politics&userid=202206&distro=PC&mode=json&limit=1'
headers = {'User-Agent': 'Mozilla/5.0', 'referer': 'https://new.qq.com/ch/politics/'}
res = requests.get(url, headers=headers)
json_data = res.json()
news_list = json_data.get('data',{}).get('items', [])
for news in news_list:
title = news.get('title')
time = news.get('updateTimeStr')
url = news.get('url')
article_res = requests.get(url, headers=headers)
soup = BeautifulSoup(article_res.text, 'html.parser')
content = soup.select('.content-article')[0].text.strip()
print(title, time, content)

首先导入需要用到的库requests和BeautifulSoup。我们需要去找到请求的链接,这里通过F12查看Network选项卡,先在首页找到想要爬取的内容,然后通过抓包分析请求链接,获取到的数据是json格式。根据json格式取到我们需要的数据。
然后遍历每一篇文章的链接,获取到每篇文章详情页的html内容。通过BeautifulSoup解析html,把内容取出来,这里通过class选择器获取到文章内容的节点。最终输出每篇文章的标题、发布时间、以及文章内容。
Python爬取QQ看点只需几行代码,实现快速爬取新闻,供需要的人进行数据分析或其他用途。