温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用Python怎么爬取微博热搜关键词

发布时间:2021-05-09 08:01:00 来源:亿速云 阅读:526 作者:Leah 栏目:编程语言

今天就跟大家聊聊有关使用Python怎么爬取微博热搜关键词,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。

python是什么意思

Python是一种跨平台的、具有解释性、编译性、互动性和面向对象的脚本语言,其最初的设计是用于编写自动化脚本,随着版本的不断更新和新功能的添加,常用于用于开发独立的项目和大型项目。

一、爬取微博热搜关键词需要的第三方库

1、requests

2、BeautifulSoup 美味汤

3、worldcloud 词云

4、jieba 中文分词

5、matplotlib 绘图

二、爬取微博热搜关键词代码示例

import requests
import wordcloud
import jieba
from bs4 import BeautifulSoup
from matplotlib import pyplot as plt
from pylab import mpl

#设置字体
mpl.rcParams['font.sans-serif'] = ['SimHei']
mpl.rcParams['axes.unicode_minus'] = False

url = 'https://s.weibo.com/top/summary?Refer=top_hot&topnav=1&wvr=6'

try:
    #获取数据
    r = requests.get(url)
    r.raise_for_status()
    r.encoding = r.apparent_encoding
    soup = BeautifulSoup(r.text,'html.parser')
    data = soup.find_all('a')
    d_list = []
    for item in data:
        d_list.append(item.text)
    words = d_list[4:-11:]
    #中文分词
    result = list(jieba.cut(words[0]))
    for word in words[1::]:
        result.extend(jieba.cut(word))
    redata = []
    for it in result:
        if len(it) <= 1:
            continue
        else:
            redata.append(it)
    result_str = ' '.join(redata)
    #输出词云图
    font = r'C:\Windows\Fonts\simhei.ttf'
    w = wordcloud.WordCloud(font_path=font,width=600,height=400)
    w.generate(result_str)
    w.to_file('微博热搜关键词词云.png')
    key = list(set(redata))
    x,y = [],[]
    #筛选数据
    for st in key:
        count = redata.count(st)
        if count <= 1:
            continue
        else:
            x.append(st)
            y.append(count)
    x.sort()
    y.sort()
    #绘制结果图
    plt.plot(x,y)
    plt.show()
except Exception as e:
    print(e)

看完上述内容,你们对使用Python怎么爬取微博热搜关键词有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI