python 爬虫抓取百度热搜

实现思路:

第1步、在百度热搜页获取热搜元素

元素类名为category-wrap_iQLoo 即我们只需要获取类名category-wrap_为前缀的元素

第2步、编写python脚本实现爬虫

复制代码
import requests
from bs4 import BeautifulSoup

url = 'https://top.baidu.com/board?tab=realtime'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36'
}
response = requests.get(url, headers=headers)
response.encoding = response.apparent_encoding
soup = BeautifulSoup(response.text, 'html.parser')
hot_searches = []
# 使用CSS选择器匹配类名前缀为'category-wrap_'的元素
category_wrap_prefix_elements = soup.select('[class^="category-wrap_"]')
# 遍历并打印这些元素
for element in category_wrap_prefix_elements:
    title = element.find('div', class_='c-single-text-ellipsis').get_text().strip()
    link = element.find('a')['href']
    print(title, link)
    hot_searches.append({title, link})
print(hot_searches)

控制台打印

相关推荐
小小测试开发4 小时前
安装 Python 3.10+
开发语言·人工智能·python
梦想不只是梦与想5 小时前
Python 中的装饰器
python·装饰器
我叫唧唧波5 小时前
Python+AI 全栈学习笔记
人工智能·python·学习
AAA大运重卡何师傅(专跑国道)6 小时前
【无标题】
开发语言·c#
copyer_xyf6 小时前
Python 异常处理
前端·后端·python
XBodhi.6 小时前
Visual Studio C++ 语法错误: 缺少“;”(在“return”的前面)
开发语言·c++·visual studio
麻雀飞吧6 小时前
期货多合约策略目标持仓怎么更新才不乱
python·区块链
Cthy_hy6 小时前
拓扑排序超详解:原理 + Kahn 贪心算法
python·算法·贪心算法
LSssT.7 小时前
【01】Python 机器学习
开发语言·python
为爱停留7 小时前
给智能体装上「刹车」:中断(Interrupts)与人工审批全解析
python