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)

控制台打印

相关推荐
ituff3 分钟前
微软认证考试又免费了
后端·python·flask
郝学胜-神的一滴3 分钟前
Linux命名管道:创建与原理详解
linux·运维·服务器·开发语言·c++·程序人生·个人开发
c***42106 分钟前
爬虫基础之爬取某基金网站+数据分析
爬虫·数据挖掘·数据分析
2501_9416233221 分钟前
C++高性能网络服务器与epoll实战分享:大规模并发连接处理与事件驱动优化经验
开发语言·php
晚风(●•σ )29 分钟前
C++语言程序设计——11 C语言风格输入/输出函数
c语言·开发语言·c++
likuolei1 小时前
XML 元素 vs. 属性
xml·java·开发语言
X***48961 小时前
C源代码生成器
c语言·开发语言
梁正雄1 小时前
2、Python流程控制
开发语言·python
catchadmin1 小时前
PHP True Async RFC 被拒——原生异步离 PHP 还有多远?
开发语言·php
J***79391 小时前
PHP在电商中的Magento
开发语言·php