用Python爬取微博热搜,标题,链接的完整代码
时间: 2024-12-22 22:13:23 浏览: 71
在Python中,我们可以使用`requests`库获取网页内容,然后使用`BeautifulSoup`库解析HTML结构,抓取微博热搜的标题和链接。由于微博热搜的具体API和结构可能会有变化,这里提供一个基于公开可用资源的基本示例,用于获取页面上的热点数据,而不是直接从官方API获取:
```python
import requests
from bs4 import BeautifulSoup
# 微博热搜页面URL
url = 'https://s.weibo.com/top/summary'
def get_weibo_hot():
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
# 发送GET请求
response = requests.get(url, headers=headers)
# 检查请求是否成功
if response.status_code == 200:
# 解析HTML
soup = BeautifulSoup(response.text, 'lxml')
# 找到包含热搜信息的部分
hot_list = soup.find('div', {'class': 'hot-list'})
# 查找每个热搜项
for item in hot_list.find_all('li'):
title = item.find('a', {'class': 'title'}).text.strip() # 热搜标题
link = item.find('a')['href'] # 热搜链接
print(f"标题: {title}\n链接: {link}\n")
else:
print("请求失败,状态码:", response.status_code)
get_weibo_hot()
```
注意:这只是一个基本示例,实际的微博热搜数据可能需要使用微博提供的API或其他技术手段获取,而且频繁抓取可能会违反微博的服务条款。
阅读全文
相关推荐


















