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)

控制台打印

相关推荐
CoderCodingNo5 分钟前
【GESP】C++五级练习题 luogu-P1865 A % B Problem
开发语言·c++·算法
陳103011 分钟前
C++:红黑树
开发语言·c++
一切尽在,你来17 分钟前
C++ 零基础教程 - 第 6 讲 常用运算符教程
开发语言·c++
泉-java18 分钟前
第56条:为所有导出的API元素编写文档注释 《Effective Java》
java·开发语言
0思必得019 分钟前
[Web自动化] Selenium处理滚动条
前端·爬虫·python·selenium·自动化
沈浩(种子思维作者)32 分钟前
系统要活起来就必须开放包容去中心化
人工智能·python·flask·量子计算
2301_7903009637 分钟前
Python数据库操作:SQLAlchemy ORM指南
jvm·数据库·python
weixin_4997715538 分钟前
C++中的组合模式
开发语言·c++·算法
初级代码游戏38 分钟前
套路化编程 C# winform 自适应缩放布局
开发语言·c#·winform·自动布局·自动缩放
_waylau42 分钟前
鸿蒙架构师修炼之道-架构师的职责是什么?
开发语言·华为·harmonyos·鸿蒙