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)

控制台打印

相关推荐
dialect_6 小时前
KMP算法
开发语言·c++·算法
总要学点什么7 小时前
第89篇:三维特效-螺旋圆效果——让螺旋臂卷起一圈圈外扩的涟漪
开发语言·javascript·ecmascript·webgl·cesium·空间分析·1024程序员节
前端精髓7 小时前
结构化输出with_structured_output(抽卡)
python·langchain
尹人入圣8 小时前
目前热门的IP驱动产业新场景新工具
网络·python·网络协议·tcp/ip
开开心心_Every8 小时前
快速隐藏程序工具自定义快捷键一键切换
java·开发语言·前端·spring·智能手机·word·intellij-idea
chenbingjie_c8 小时前
C++ 多态完全指南:从虚函数重写到虚函数表原理
开发语言·c++
Nuanyt9 小时前
Agent 学习笔记(下篇三):上线工程、进阶选择与操作界面(Stage 7 / 7.5 / 8 + 延伸路线)
笔记·python·学习·memory·aiagent·harness
吴卫斌9 小时前
定投ETF实战指南(四):行业/主题ETF——定投的“进攻端“
开发语言·python·股票·量化
2601_967987379 小时前
Python——入门级(定义功能def函数)
python·函数·可变参数·默认参数·关键字参数
超级架构师10 小时前
PRAXO-CORE 2.5.0:用 conformance 和显式边界构建 Go Agent 框架
开发语言·人工智能·后端·golang·ai编程·智能体框架·praxo-core