python爬取微博热搜数据
时间: 2023-07-29 09:06:25 浏览: 134
好的,您可以使用 Python 的 requests 库和 BeautifulSoup 库来爬取微博热搜数据。以下是一个简单的代码示例:
```python
import requests
from bs4 import BeautifulSoup
url = 'https://s.weibo.com/top/summary?cate=realtimehot'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for item in soup.select('#pl_top_realtimehot tr'):
try:
rank = item.select('.td-01')[0].get_text().strip()
title = item.select('.td-02 a')[0].get_text().strip()
hot = item.select('.td-02 span')[0].get_text().strip()
print(rank, title, hot)
except:
pass
```
该代码会爬取微博热搜榜的数据,并输出每一项的排名、标题和热度。请注意,网页结构可能会随时更改,所以代码可能需要根据实际情况进行调整。
相关问题
如何用python爬取微博热搜数据然后导入一个名字为1的一个文档里面
可以使用Python中的requests和beautifulsoup4库来实现爬取微博热搜数据并导入文档。
以下是示例代码:
```python
import requests
from bs4 import BeautifulSoup
# 爬取微博热搜页面
url = 'https://s.weibo.com/top/summary?cate=realtimehot'
response = requests.get(url)
# 使用beautifulsoup解析页面
soup = BeautifulSoup(response.text, 'html.parser')
# 获取热搜列表
hot_list = soup.find_all('td', class_='td-02')
# 将热搜写入文件
with open('1.txt', 'w', encoding='utf-8') as f:
for i, hot in enumerate(hot_list):
f.write(f'{i+1}. {hot.text.strip()}\n')
```
运行以上代码,即可将微博热搜数据写入名为1的文档中。
如何用python爬取微博热搜数据然后导入一个名字为1的一个文档里面,并且对其进行分词生成词云
可以使用Python中的jieba和wordcloud库来对微博热搜数据进行分词并生成词云。
以下是示例代码:
```python
import requests
from bs4 import BeautifulSoup
import jieba
from wordcloud import WordCloud
# 爬取微博热搜页面
url = 'https://s.weibo.com/top/summary?cate=realtimehot'
response = requests.get(url)
# 使用beautifulsoup解析页面
soup = BeautifulSoup(response.text, 'html.parser')
# 获取热搜列表
hot_list = soup.find_all('td', class_='td-02')
# 将热搜写入文件,并进行分词
with open('1.txt', 'w', encoding='utf-8') as f:
text = ''
for i, hot in enumerate(hot_list):
text += hot.text.strip() + ' '
f.write(f'{i+1}. {hot.text.strip()}\n')
words = jieba.lcut(text)
# 生成词云
wc = WordCloud(width=800, height=600, background_color='white', font_path='simhei.ttf')
wc.generate(' '.join(words))
wc.to_file('1.png')
```
运行以上代码,即可将微博热搜数据写入名为1的文档中,并生成名为1.png的词云图片。需要注意的是,以上代码中`simhei.ttf`需要替换为本地计算机中的中文字体路径。
阅读全文
相关推荐
















