python爬取微博话题
时间: 2023-09-12 20:04:11 浏览: 156
要爬取微博话题,可以使用Python中的requests和BeautifulSoup库来实现。具体步骤如下:
1. 打开微博网页版,搜索想要爬取的话题,并复制该话题的url。
2. 使用requests库发送GET请求获取该话题的html源代码。
```python
import requests
url = 'https://weibo.cn/search/mblog?hideSearchFrame=&keyword=%23Python%E5%BC%80%E5%8F%91%23'
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.36 Edge/16.16299'
}
response = requests.get(url, headers=headers)
html = response.content
```
3. 使用BeautifulSoup库解析html源代码,并获取该话题的所有微博信息。
```python
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, 'lxml')
weibo_list = soup.find_all('div', class_='c')
```
4. 遍历微博列表,获取每条微博的内容、发布时间、点赞数、评论数、转发数等信息。
```python
for weibo in weibo_list:
# 获取微博内容
content = weibo.find('span', class_='ctt').get_text()
# 获取发布时间
time = weibo.find('span', class_='ct').get_text().split('\xa0')[0]
# 获取点赞数、评论数、转发数
stats = weibo.find_all('a')
up_num = stats[0].text.split('[')[1].split(']')[0]
repost_num = stats[1].text.split('[')[1].split(']')[0]
comment_num = stats[2].text.split('[')[1].split(']')[0]
# 输出微博信息
print('微博内容:', content)
print('发布时间:', time)
print('点赞数:', up_num)
print('转发数:', repost_num)
print('评论数:', comment_num)
```
以上就是使用Python爬取微博话题的基本步骤和代码示例。需要注意的是,爬取微博数据需要遵守相关法律法规和网站协议,不得用于商业用途。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![py](https://img-home.csdnimg.cn/images/20250102104920.png)