zoukankan      html  css  js  c++  java
  • 百度热搜爬取并制作词云图

    1.先找到百度热搜风云榜。

    2.需要插件selenium,这个插件使用起来非常方便,可以模拟打开浏览器,找到数据的位置。

       使用的时候要导入

    from selenium.webdriver import Chrome,ChromeOptions
    

      还需要下载一个谷歌驱动,在创建浏览器对象的时候要指明驱动的位置,否则无法使用

    3.接下来就可以定位元素进行爬取,这儿我是用的是Xpath定位,并将其保存到数据库

     1 def baidu_hot():
     2     url = "http://top.baidu.com/buzz?b=42&c=513&fr=topbuzz_b1_c513"
     3     option = ChromeOptions()
     4     option.add_argument("--headless")  #隐藏浏览器,在运行的时候不会自动打开浏览器
     5     res = requests.get(url)
     6     #创建浏览器对象
     7     #r"F:pycharm_projectchromedriver.exe"
     8     brower = Chrome("F:pycharm_projectchromedriver.exe")  #需要写入驱动的安装路径,否则无法使用驱动导致报错
     9     brower.get(url)
    10     contents = brower.find_elements_by_xpath('//*[@id="main"]/div[2]/div/table/tbody/tr/td[2]/a[1]')#  xpath 路径来找到热搜内容
    11     clicks = brower.find_elements_by_xpath('//*[@id="main"]/div[2]/div/table/tbody/tr/td[4]/span')  # xpath 路径找到点击量
    12     content,click = [],[]
    13     content = [i.text for i in contents]  #列表推导式来简化代码 并且保存到content列表中
    14     click = [i.text for i in clicks]
    15     brower.close()
    16     return content,click
    17 
    18 def get_serachhot():
    19         cursor = None
    20         conn = None
    21         context = baidu_hot()[0]
    22         click = baidu_hot()[1]
    23         dict = {context[i]:click[i] for i in range(len(context))}
    24         print(f'{time.asctime()}开始更新热搜榜')
    25         conn,cursor = get_conn()
    26         sql = "insert into baidu_hot(datetime,content,click) values(%s,%s,%s)"
    27         sql_clean = "TRUNCATE TABLE baidu_hot"
    28         cursor.execute(sql_clean)
    29         ts = time.strftime("%Y-%m-%d %X")
    30         for key,value in dict.items():
    31             cursor.execute(sql,(ts,key,value))
    32         conn.commit()
    33         print(f'{time.asctime()}更新热搜榜完毕')
    34         close_conn(conn,cursor)
    热搜爬取

     这样就把实时数据爬取到的数据库

    4.接下来可以进行词云图的制作

      4.1要想制作词云图,要先用ajax把数据取从数据库读出来。

     1 @app.route('/r2')
     2 def get_r2_data():
     3     """
     4 
     5     :return:  返回最近的20条热搜
     6     """
     7     sql = 'select content,click from baidu_hot order by click desc limit 20'
     8     res = query(sql) #格式 (('杭州杀妻嫌犯疑似涉及另一桩命案', 819272), ('四川安岳男子趁妻子熟睡将其杀害', 795389))
     9     d = []
    10     for i in res:
    11         k = i[0]  # 移除热搜数字
    12         v = i[1] # 获取热搜数字
    13         ks = extract_tags(k)  # 使用jieba 提取关键字
    14         for j in ks:
    15             if not j.isdigit():
    16                 d.append({"name": j, "value": v})
    17     return jsonify({"kws": d})
    取出热搜数据

     4.2用echarts制作词云图

          <script src="../static/js/echarts-wordcloud.min.js"></script>

           这个云图的包是必不可少的

           最后进行云图的数据配置

     1 var ec_right2 = echarts.init(document.getElementById('r2'), "dark");
     2 var ec_right2_option = {
     3                         // backgroundColor: '#515151',
     4                         title : {
     5                             text : "7日百度热搜",
     6                             textStyle : {
     7                                 color : 'white',
     8                             },
     9                             left : 'left'
    10                         },
    11                         tooltip: {
    12                             show: false
    13                         },
    14                         series: [{
    15                                 type: 'wordCloud',
    16                                 // drawOutOfBound:true,
    17                                 gridSize: 1,
    18                                 sizeRange: [12, 55],
    19                                 rotationRange: [-45, 0, 45, 90],
    20                                 // maskImage: maskImage,
    21                                 textStyle: {
    22                                     normal: {
    23                                         color: function () {
    24                                             return 'rgb(' +
    25                                                     Math.round(Math.random() * 255) +
    26                                                     ', ' + Math.round(Math.random() * 255) +
    27                                                     ', ' + Math.round(Math.random() * 255) + ')'
    28                                         }
    29                                     }
    30                                 },
    31                                 // left: 'center',
    32                                 // top: 'center',
    33                                 // //  '96%',
    34                                 // // height: '100%',
    35                                 right: null,
    36                                 bottom: null,
    37                                 //  300,
    38                                 // height: 200,
    39                                 // top: 20,
    40                                 data:  []
    41                             }]
    42                     }
    43 
    44 ec_right2.setOption(ec_right2_option);
    词云图配置

    这样工作就基本完成了,来看看效果:

  • 相关阅读:
    A1023 Have Fun with Numbers (20分)(大整数四则运算)
    A1096 Consecutive Factors (20分)(质数分解)
    A1078 Hashing (25分)(哈希表、平方探测法)
    A1015 Reversible Primes (20分)(素数判断,进制转换)
    A1081 Rational Sum (20分)
    A1088 Rational Arithmetic (20分)
    A1049 Counting Ones (30分)
    A1008 Elevator (20分)
    A1059 Prime Factors (25分)
    A1155 Heap Paths (30分)
  • 原文地址:https://www.cnblogs.com/g414056667/p/13494385.html
Copyright © 2011-2022 走看看