溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python爬蟲中如何爬取2019中國(guó)好聲音評(píng)論

發(fā)布時(shí)間:2021-08-21 14:43:28 來源:億速云 閱讀:171 作者:小新 欄目:開發(fā)技術(shù)

這篇文章主要為大家展示了“python爬蟲中如何爬取2019中國(guó)好聲音評(píng)論”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“python爬蟲中如何爬取2019中國(guó)好聲音評(píng)論”這篇文章吧。

1.網(wǎng)頁(yè)分析部分

本文爬取的是騰訊視頻評(píng)論,第六期的評(píng)論地址是:http://coral.qq.com/4093121984

每頁(yè)有10條評(píng)論,點(diǎn)擊“查看更多評(píng)論”,可將新的評(píng)論加載進(jìn)來,通過多次加載,可以發(fā)現(xiàn)我們要找的評(píng)論就在以v2開頭的js類型的響應(yīng)中。

請(qǐng)求為GET請(qǐng)求,地址是http://coral.qq.com/article/4093121984/comment/v2 ,通過傳入不同的參數(shù)返回不同的評(píng)論內(nèi)容。

python爬蟲中如何爬取2019中國(guó)好聲音評(píng)論

python爬蟲中如何爬取2019中國(guó)好聲音評(píng)論

經(jīng)過對(duì)比發(fā)現(xiàn),參數(shù)不同的地方只有兩點(diǎn),"cursor"和""。

先看"cursor":第一頁(yè)的"cursor"是0,后面每一頁(yè)的都是前一頁(yè)響應(yīng)中"last"的值

再看下"":第一頁(yè)的值似乎是隨機(jī)生成的,而后面每一頁(yè)都在前一頁(yè)的基礎(chǔ)上加1

python爬蟲中如何爬取2019中國(guó)好聲音評(píng)論

python爬蟲中如何爬取2019中國(guó)好聲音評(píng)論

OK,找到規(guī)律后,開始爬取每一頁(yè)的評(píng)論

2.爬蟲部分

(1)導(dǎo)入需要的庫(kù)

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,"內(nèi)容為空,跳過")
    pass

(2)爬取評(píng)論內(nèi)容

這里總共爬取了三種類型的數(shù)據(jù):用戶評(píng)論、用戶昵稱、用戶所在地區(qū)

#評(píng)論請(qǐng)求地址
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'
}
# 第一頁(yè)
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()),"請(qǐng)求失敗。",e)
  else:
    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),"請(qǐng)求成功。")
  content = html.content.decode('utf-8')
  sep1 = '"last":"(.*?)"' # 下一個(gè) cursor
  sep2 = '"content":"(.*?)"' # 評(píng)論
  sep3 = '"nick":"(.*?)"' # 昵稱
  sep4 = '"region":"(.*?)"' # 地區(qū)
  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中國(guó)好聲音評(píng)論

python爬蟲中如何爬取2019中國(guó)好聲音評(píng)論

python爬蟲中如何爬取2019中國(guó)好聲音評(píng)論

(3)對(duì)用戶評(píng)論進(jìn)行分詞

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 #返回分詞后的數(shù)據(jù)

(4)生成詞云

#詞云形狀圖片
img1 = 'lib/fangxing.png'
img2 = 'lib/xin.png'
#詞云字體
font = 'lib/simsun.ttc'
def create_word_cloud(file_path,img):
  # 設(shè)置詞云形狀圖片
  wc_mask = np.array(Image.open(img))
  # 設(shè)置詞云的一些配置,如:字體,背景色,詞云形狀,大小
  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))
  # 在只設(shè)置mask的情況下,你將會(huì)得到一個(gè)擁有圖片形狀的詞云
  plt.imshow(wc, interpolation="bilinear")
  plt.axis("off")
  #plt.figure()
  plt.show()

效果如下:

python爬蟲中如何爬取2019中國(guó)好聲音評(píng)論

python爬蟲中如何爬取2019中國(guó)好聲音評(píng)論

(5)對(duì)用戶地區(qū)統(tǒng)計(jì)分析

國(guó)外地區(qū)忽略了,這里只對(duì)國(guó)內(nèi)地區(qū)進(jìn)行了分析

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 '中國(guó)' 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))
  # 構(gòu)建數(shù)據(jù)
  x_data = province_uniq
  y_data = province_count
  # 自定義字體屬性
  fp = fmgr.FontProperties(fname='lib/simsun.ttc')
  bar_width = 0.7
  # Y軸數(shù)據(jù)使用range(len(x_data)
  plt.barh(y=range(len(x_data)), width=y_data, label='count',
       color='steelblue', alpha=0.8, height=bar_width)
  # 在柱狀圖上顯示具體數(shù)值, ha參數(shù)控制水平對(duì)齊方式, va控制垂直對(duì)齊方式
  for y, x in enumerate(y_data):
    plt.text(x+10, y - bar_width / 2, '%s' % x, ha='center', va='bottom')
  # 為Y軸設(shè)置刻度值
  plt.yticks(np.arange(len(x_data)) + bar_width / 2, x_data,fontproperties=fp)
  # 設(shè)置標(biāo)題
  plt.title("各地區(qū)參與評(píng)論用戶量",fontproperties=fp)
  # 為兩條坐標(biāo)軸設(shè)置名稱
  plt.xlabel("人數(shù)",fontproperties=fp)
  plt.ylabel("地區(qū)",fontproperties=fp)
  # 顯示圖例
  plt.legend()
  plt.show()

效果如下:

python爬蟲中如何爬取2019中國(guó)好聲音評(píng)論

以上是“python爬蟲中如何爬取2019中國(guó)好聲音評(píng)論”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI