python爬虫 2019中国好声音评论爬取过程解析


Posted in Python onAugust 26, 2019

2019中国好声音火热开播,作为一名“假粉丝”,这一季每一期都刷过了,尤其刚播出的第六期开始正式的battle。视频视频看完了,那看下大家都是怎样评论的。

1.网页分析部分

本文爬取的是腾讯视频评论,第六期的评论地址是:http://coral.qq.com/4093121984

每页有10条评论,点击“查看更多评论”,可将新的评论加载进来,通过多次加载,可以发现我们要找的评论就在以v2开头的js类型的响应中。

请求为GET请求,地址是http://coral.qq.com/article/4093121984/comment/v2 ,通过传入不同的参数返回不同的评论内容。

python爬虫 2019中国好声音评论爬取过程解析

python爬虫 2019中国好声音评论爬取过程解析

经过对比发现,参数不同的地方只有两点,"cursor"和""。

先看"cursor":第一页的"cursor"是0,后面每一页的都是前一页响应中"last"的值

再看下"":第一页的值似乎是随机生成的,而后面每一页都在前一页的基础上加1

python爬虫 2019中国好声音评论爬取过程解析

python爬虫 2019中国好声音评论爬取过程解析

OK,找到规律后,开始爬取每一页的评论

2.爬虫部分

(1)导入需要的库

import requests
import re
import random
import time
import json
import jieba
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.font_manager as fmgr
from wordcloud import WordCloud
from common import user_agent #自定义
from common import my_fanction #自定义

其中common文件夹中自定义了一些方法:

user_agent

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@File : user_agent.py
@Author: Fengjicheng
@Date : 2019/8/11
@Desc :
'''
user_agent_list = [
    # Opera
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 OPR/26.0.1656.60",
    "Opera/8.0 (Windows NT 5.1; U; en)",
    "Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.50",
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 9.50",
    # Firefox
    "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0",
    "Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10",
    # Safari
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2",
    # chrome
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11",
    "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16",
    # 360
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36",
    "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko",
    # 淘宝浏览器
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11",
    # 猎豹浏览器
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER",
    "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)",
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)",
    # QQ浏览器
    "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)",
    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)",
    # sogou浏览器
    "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 SE 2.X MetaSr 1.0",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; SE 2.X MetaSr 1.0)",
    # maxthon浏览器
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.4.3.4000 Chrome/30.0.1599.101 Safari/537.36",
    # UC浏览器
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 UBrowser/4.0.3214.0 Safari/537.36",
  ]

my_function

#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@File : file_writte.py
@Author: Fengjicheng
@Date : 2019/8/24
@Desc :
'''
def file_write(file_name,content):
  if content:
    if type(content) == list:
      for i in content:
        with open(file_name,'a',encoding='utf-8') as f:
          f.write(i + '\n')
    if type(content) == str:
      with open(file_name, 'a', encoding='utf-8') as f:
        f.write(content)
  else:
    print(content,"内容为空,跳过")
    pass

(2)爬取评论内容

这里总共爬取了三种类型的数据:用户评论、用户昵称、用户所在地区

#评论请求地址
url = 'http://coral.qq.com/article/4093121984/comment/v2'
agent = random.choice(user_agent.user_agent_list)
header = {
'Host': 'video.coral.qq.com',
'User-Agent': agent,
'Accept': '*/*',
'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive',
'Referer': 'https://page.coral.qq.com/coralpage/comment/video.html',
'TE': 'Trailers'
}
# 第一页
cursor = '0'
vid = 1566724116229

def get_comment(a,b):
  parameter = {
  'callback': '_varticle4093121984commentv2',
  'orinum': '10',
  'oriorder': 'o',
  'pageflag': '1',
  'cursor': a,
  'scorecursor': '0',
  'orirepnum': '2',
  'reporder': 'o',
  'reppageflag': '1',
  'source': '1',
  '_': str(b)
  }
  try:
    html = requests.get(url,params=parameter,headers=header)
  except Exception as e:
    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),"请求失败。",e)
  else:
    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),"请求成功。")
  content = html.content.decode('utf-8')
  sep1 = '"last":"(.*?)"' # 下一个 cursor
  sep2 = '"content":"(.*?)"' # 评论
  sep3 = '"nick":"(.*?)"' # 昵称
  sep4 = '"region":"(.*?)"' # 地区
  global cursor
  cursor = re.compile(sep1).findall(content)[0]
  comment = re.compile(sep2).findall(content)
  nick = re.compile(sep3).findall(content)
  region = re.compile(sep4).findall(content)
  my_fanction.file_write('txt/comment.txt',comment)
  my_fanction.file_write('txt/nick.txt',nick)
  my_fanction.file_write('txt/region.txt',region)

效果如下:

python爬虫 2019中国好声音评论爬取过程解析

python爬虫 2019中国好声音评论爬取过程解析

python爬虫 2019中国好声音评论爬取过程解析

(3)对用户评论进行分词

def cut_word(file_path):
  with open(file_path,'r',encoding='utf-8') as f:
    comment_txt = f.read()
    wordlist = jieba.cut(comment_txt, cut_all=True)
    wl = " ".join(wordlist)
    print(wl)
    return wl #返回分词后的数据

(4)生成词云

#词云形状图片
img1 = 'lib/fangxing.png'
img2 = 'lib/xin.png'
#词云字体
font = 'lib/simsun.ttc'
def create_word_cloud(file_path,img):
  # 设置词云形状图片
  wc_mask = np.array(Image.open(img))
  # 设置词云的一些配置,如:字体,背景色,词云形状,大小
  wc = WordCloud(background_color="white", max_words=200, mask=wc_mask, scale=4,
          max_font_size=50, random_state=42, font_path=font)
  # 生成词云
  wc.generate(cut_word(file_path))
  # 在只设置mask的情况下,你将会得到一个拥有图片形状的词云
  plt.imshow(wc, interpolation="bilinear")
  plt.axis("off")
  #plt.figure()
  plt.show()

效果如下:

python爬虫 2019中国好声音评论爬取过程解析

python爬虫 2019中国好声音评论爬取过程解析

(5)对用户地区统计分析

国外地区忽略了,这里只对国内地区进行了分析

def create_region_histogram():
  with open('txt/region.txt','r',encoding='utf-8') as f:
    country_list = f.readlines()
    country_list = [x.strip() for x in country_list if x.strip() != '::']
  sep1 = ':'
  pattern1 = re.compile(sep1)
  province_lit = []
  province_count = []
  other_list = []
  other_count = []
  for country in country_list:
    country_detail = re.split(pattern1,country)
    if '中国' in country_detail:
      if country_detail[1] != '':
        province_lit.append(country_detail[1])
    else:
      other_list.append(country_detail[0])
  province_uniq = list(set(province_lit))
  other_uniq = list(set(other_list))
  for i in province_uniq:
    province_count.append(province_lit.count(i))
  for i in other_uniq:
    other_count.append(other_list.count(i))
  # 构建数据
  x_data = province_uniq
  y_data = province_count
  # 自定义字体属性
  fp = fmgr.FontProperties(fname='lib/simsun.ttc')
  bar_width = 0.7
  # Y轴数据使用range(len(x_data)
  plt.barh(y=range(len(x_data)), width=y_data, label='count',
       color='steelblue', alpha=0.8, height=bar_width)
  # 在柱状图上显示具体数值, ha参数控制水平对齐方式, va控制垂直对齐方式
  for y, x in enumerate(y_data):
    plt.text(x+10, y - bar_width / 2, '%s' % x, ha='center', va='bottom')
  # 为Y轴设置刻度值
  plt.yticks(np.arange(len(x_data)) + bar_width / 2, x_data,fontproperties=fp)
  # 设置标题
  plt.title("各地区参与评论用户量",fontproperties=fp)
  # 为两条坐标轴设置名称
  plt.xlabel("人数",fontproperties=fp)
  plt.ylabel("地区",fontproperties=fp)
  # 显示图例
  plt.legend()
  plt.show()

效果如下:

python爬虫 2019中国好声音评论爬取过程解析

github地址:https://github.com/FJCAAAAA/python-spider

注:本文章只用于学习使用

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
用Python进行TCP网络编程的教程
Apr 29 Python
django轻松使用富文本编辑器CKEditor的方法
Mar 30 Python
利用matplotlib+numpy绘制多种绘图的方法实例
May 03 Python
Flask框架使用DBUtils模块连接数据库操作示例
Jul 20 Python
python创建文件时去掉非法字符的方法
Oct 31 Python
解决安装pycharm后不能执行python脚本的问题
Jan 19 Python
如何用C代码给Python写扩展库(Cython)
May 17 Python
python银行系统实现源码
Oct 25 Python
python matplotlib饼状图参数及用法解析
Nov 04 Python
python框架Django实战商城项目之工程搭建过程图文详解
Mar 09 Python
在脚本中单独使用django的ORM模型详解
Apr 01 Python
在Anaconda3下使用清华镜像源安装TensorFlow(CPU版)
Apr 19 Python
解决Python计算矩阵乘向量,矩阵乘实数的一些小错误
Aug 26 #Python
对Python中一维向量和一维向量转置相乘的方法详解
Aug 26 #Python
python 中xpath爬虫实例详解
Aug 26 #Python
Python使用itchat模块实现群聊转发,自动回复功能示例
Aug 26 #Python
python自动保存百度盘资源到百度盘中的实例代码
Aug 26 #Python
Python3 文章标题关键字提取的例子
Aug 26 #Python
python实现的爬取电影下载链接功能示例
Aug 26 #Python
You might like
1 Tube Radio
2021/03/02 无线电
PHP文件上传实例详解!!!
2007/01/02 PHP
php导出word文档与excel电子表格的简单示例代码
2014/03/08 PHP
详细分析PHP 命名空间(namespace)
2020/06/30 PHP
拖动一个HTML元素
2006/12/22 Javascript
asp批量修改记录的代码
2008/06/25 Javascript
jQuery可见性过滤器:hidden和:visibility用法实例
2015/06/24 Javascript
js仿支付宝填写支付密码效果实现多方框输入密码
2016/03/09 Javascript
分享jQuery网页元素拖拽插件
2020/12/01 Javascript
Vuejs第十三篇之组件——杂项
2016/09/09 Javascript
bootstrap基础知识学习笔记
2016/11/02 Javascript
AngularJS+bootstrap实现动态选择商品功能示例
2017/05/17 Javascript
9种使用Chrome Firefox 自带调试工具调试javascript技巧
2017/12/22 Javascript
vue实现拖拽效果
2019/12/23 Javascript
Windows下安装 node 的版本控制工具 nvm
2020/02/06 Javascript
vue集成openlayers加载geojson并实现点击弹窗教程
2020/09/24 Javascript
JavaScript代码实现简单计算器
2020/12/27 Javascript
[36:22]VP vs Serenity 2018国际邀请赛小组赛BO2 第一场 8.16
2018/08/17 DOTA
python检测某个变量是否有定义的方法
2015/05/20 Python
分享Python开发中要注意的十个小贴士
2016/08/30 Python
Python+matplotlib实现填充螺旋实例
2018/01/15 Python
Python运维自动化之nginx配置文件对比操作示例
2018/08/29 Python
python实现画循环圆
2019/11/23 Python
浅谈多卡服务器下隐藏部分 GPU 和 TensorFlow 的显存使用设置
2020/06/30 Python
手把手教你如何用Pycharm2020.1.1配置远程连接的详细步骤
2020/08/07 Python
尤妮佳moony海外旗舰店:日本殿堂级纸尿裤品牌
2018/02/23 全球购物
The Body Shop美体小铺西班牙官网:天然化妆品
2019/06/21 全球购物
Super-Pharm波兰:药房和香水在一个地方
2020/08/18 全球购物
Ego Shoes官网:英国时髦鞋类品牌
2020/10/19 全球购物
作为网站管理者应当如何防范XSS
2014/08/16 面试题
Java编程面试题
2016/04/04 面试题
个人工作作风整改措施思想汇报
2014/10/13 职场文书
公路施工安全责任书
2015/05/08 职场文书
党校培训学习心得体会
2016/01/06 职场文书
Java使用JMeter进行高并发测试
2021/11/23 Java/Android
PostGIS的安装与入门使用指南
2022/01/18 PostgreSQL