import requests
from bs4 import BeautifulSoup
def get_baidu_hot():
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)
soup = BeautifulSoup(response.text, 'html.parser')
hot_items = soup.find_all('div', class_='title')
hot_searches = []
for item in hot_items[:10]:
rank = item.find('span').get_text()
keyword = item.find('a').get_text()
hot_searches.append(f'{rank}. {keyword}')
return hot_searches
# 调用函数获取百度前10条热搜
results = get_baidu_hot()
# 打印结果
for result in results:
print(result)
在上述代码中,我们使用requests
库发送HTTP请求获取百度热搜榜单的页面内容。然后使用BeautifulSoup
库解析HTML页面,并通过CSS选择器定位到热搜关键词所在的HTML元素。最后,我们提取前10个热搜关键词的排名和关键词内容,并存储在hot_searches
列表中。
注意,为了模拟浏览器的请求,我们在代码中添加了User-Agent
头部信息,这有助于避免被网站识别为爬虫。同时,请确保安装了requests
和beautifulsoup4
库,可以使用pip install requests beautifulsoup4
命令进行安装。
福利
为方便大家自学软件测试,分享更多测试资料
主体内容包含:测试面试题,功能测试、性能测试、自动化测试等学习知识内容。
软件测试自学资料包领取