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)

控制台打印

相关推荐
yunhuibin7 小时前
GoogLeNet学习
人工智能·python·深度学习·神经网络·学习
m0_531237177 小时前
C语言-指针终阶
c语言·开发语言
散峰而望7 小时前
C++ 启程:从历史到实战,揭开命名空间的神秘面纱
c语言·开发语言·数据结构·c++·算法·github·visual studio
易辰君8 小时前
【Python爬虫实战】正则:中文匹配与贪婪非贪婪模式详解
开发语言·爬虫·python
普通网友8 小时前
PHP语言的正则表达式
开发语言·后端·golang
黎雁·泠崖8 小时前
Java常用类核心详解(七):正则表达式 Regex 从入门到实战
java·开发语言·正则表达式
秀儿还能再秀8 小时前
正则表达式核心语法 + Python的 re 库中常用方法
python·正则表达式
xcLeigh8 小时前
Python入门:Python3 正则表达式全面学习教程
python·学习·正则表达式·教程·python3
PingdiGuo_guo8 小时前
C++数据类型、变量常量
开发语言·c++
多恩Stone9 小时前
【C++ debug】在 VS Code 中无 Attach 调试 Python 调用的 C++ 扩展
开发语言·c++·python