python爬虫--2019中国好声音评论爬取

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

1.网页分析部分

本文爬取的是腾讯视频评论,第六期的评论地址是:http://coral.qq.com/4093121984
每页有10条评论,点击“查看更多评论”,可将新的评论加载进来,通过多次加载,可以发现我们要找的评论就在以v2开头的js类型的响应中。

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

图二:


经过对比发现,参数不同的地方只有两点,"cursor"和""。
先看"cursor":第一页的"cursor"是0,后面每一页的都是前一页响应中"last"的值
再看下"
":第一页的值似乎是随机生成的,而后面每一页都在前一页的基础上加1
图三:

图四:

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)

效果如下:


(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()

效果如下:

(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()

效果如下:

github地址:https://github.com/FJCAAAAA/python-spider
注:本文章只用于学习使用

原文地址:https://blog.51cto.com/fengjicheng/2432450

时间: 2024-07-29 16:19:52

python爬虫--2019中国好声音评论爬取的相关文章

Python爬虫实战二之爬取百度贴吧帖子

大家好,上次我们实验了爬取了糗事百科的段子,那么这次我们来尝试一下爬取百度贴吧的帖子.与上一篇不同的是,这次我们需要用到文件的相关操作. 前言 亲爱的们,教程比较旧了,百度贴吧页面可能改版,可能代码不好使,八成是正则表达式那儿匹配不到了,请更改一下正则,当然最主要的还是帮助大家理解思路. 2016/12/2 本篇目标 1.对百度贴吧的任意帖子进行抓取 2.指定是否只抓取楼主发帖内容 3.将抓取到的内容分析并保存到文件 1.URL格式的确定 首先,我们先观察一下百度贴吧的任意一个帖子. 比如:ht

转 Python爬虫实战二之爬取百度贴吧帖子

静觅 » Python爬虫实战二之爬取百度贴吧帖子 大家好,上次我们实验了爬取了糗事百科的段子,那么这次我们来尝试一下爬取百度贴吧的帖子.与上一篇不同的是,这次我们需要用到文件的相关操作. 本篇目标 1.对百度贴吧的任意帖子进行抓取 2.指定是否只抓取楼主发帖内容 3.将抓取到的内容分析并保存到文件

Python爬虫新手教程:爬取了6574篇文章,告诉你产品经理在看什么!

作为互联网界的两个对立的物种,产品汪与程序猿似乎就像一对天生的死对头:但是在产品开发链条上紧密合作的双方,只有通力合作,才能更好地推动项目发展.那么产品经理平日里面都在看那些文章呢?我们程序猿该如何投其所好呢?我爬取了人人都是产品经理栏目下的所有文章,看看产品经理都喜欢看什么. 1. 分析背景 1.1. 为什么选择「人人都是产品经理」 人人都是产品经理是以产品经理.运营为核心的学习.交流.分享平台,集媒体.培训.招聘.社群为一体,全方位服务产品人和运营人,成立8年举办在线讲座500+期,线下分享

Python爬虫系列 - 初探:爬取旅游评论

Python爬虫目前是基于requests包,下面是该包的文档,查一些资料还是比较方便. http://docs.python-requests.org/en/master/ 爬取某旅游网站的产品评论,通过分析,获取json文件需要POST指令.简单来说: GET是将需要发送的信息直接添加在网址后面发送 POST方式是发送一个另外的内容到服务器 那么通过POST发送的内容可以大概有三种,即form.json和multipart,目前先介绍前两种 1.content in form Content

Python 爬虫入门实例(爬取小米应用商店的top应用apk)

一,爬虫是什么? 爬虫就是获取网络上各种资源,数据的一种工具.具体的可以自行百度. 二,如何写简单爬虫 1,获取网页内容 可以通过 Python(3.x) 自带的 urllib,来实现网页内容的下载.实现起来很简单 import urllib.request url="http://www.baidu.com" response=urllib.request.urlopen(url) html_content=response.read() 还可以使用三方库 requests ,实现起

Python爬虫之利用正则表达式爬取内涵吧

首先,我们来看一下,爬虫前基本的知识点概括 一. match()方法: 这个方法会从字符串的开头去匹配(也可以指定开始的位置),如果在开始没有找到,立即返回None,匹配到一个结果,就不再匹配. 我们可以指定开始的位置的索引是3,范围是3-10,那么python将从第4个字符'1'开始匹配,只匹配一个结果. group()获得一个或多个分组的字符串,指定多个字符串时将以元组的形式返回,group(0)代表整个匹配的字串,不填写参数时,group()返回的是group(0). 1 import r

Python爬虫实战教程:爬取网易新闻;爬虫精选 高手技巧

前言本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. stars声明很多小伙伴学习Python过程中会遇到各种烦恼问题解决不了.为此小编建了个群 624440745. 不懂的问题有老司机解决里面还有最新Python教程项目可拿,,一起相互监督共同进步! 此文属于入门级级别的爬虫,老司机们就不用看了. 本次主要是爬取网易新闻,包括新闻标题.作者.来源.发布时间.新闻正文. 首先我们打开163的网站,我们随意选择一个分类,这里我选

Python爬虫之简单的爬取百度贴吧数据

首先要使用的第类库有 urllib下的request  以及urllib下的parse  以及 time包  random包 之后我们定义一个名叫BaiduSpider类用来爬取信息 属性有 url:用来爬取的网址             headers:请求头 class BaiduSpider(object): def __init__(self): self.url = 'http://tieba.baidu.com/f?kw={}&pn={}' self.headers = {'User

python爬虫-20行代码爬取王者荣耀所有英雄图片,小白也轻轻松松

1.环境 python3.6 需要用到的库: re.os.requests 2.简介 王者荣耀可以算得上是比较受欢迎的手游之一了,应该有不少的人都入坑过农药,我们今天的目的就是要爬取王者荣耀的高清英雄壁纸,包括这些英雄的皮肤,不废话了,go! 3.分析 首先,我们打开王者荣耀的英雄资料 然后,日常F12打开浏览器的开发者工具 可以看到这里返回了一个json数据,里面包含了英雄的名字(cname),皮肤名字(skin_name),英雄id(ename)这个id后面的皮肤有用 具体某一个英雄的网址,