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)

控制台打印

相关推荐
这个人懒得名字都没写1 小时前
Python包管理新纪元:uv
python·conda·pip·uv
有泽改之_1 小时前
leetcode146、OrderedDict与lru_cache
python·leetcode·链表
是毛毛吧2 小时前
边打游戏边学Python的5个开源项目
python·开源·github·开源软件·pygame
暮乘白帝过重山2 小时前
ArkTS ForEach 参数解析:组件与键值生成器
开发语言·数据库
LiamTuc2 小时前
Java构造函数
java·开发语言
三途河畔人2 小时前
Pytho基础语法_运算符
开发语言·python·入门
Benmao⁢2 小时前
C语言期末复习笔记
c语言·开发语言·笔记·leetcode·面试·蓝桥杯
adsadswee2 小时前
Qt 样式与 QLinearGradient 渐变详解
开发语言·qt·qt样式表·qlineargradient·qss渐变效果
花月C3 小时前
个性化推荐:基于用户的协同过滤算法
开发语言·后端·算法·近邻算法
脾气有点小暴3 小时前
前端页面跳转的核心区别与实战指南
开发语言·前端·javascript