Python爬蟲新手入門教學(七):爬取騰訊視頻彈幕

前言

本文的文字及圖片來源於網絡,僅供學習、交流使用,不具備任何商業用途,若有問題請及時聯繫咱們以做處理。html

Python爬蟲、數據分析、網站開發等案例教程視頻免費在線觀看編程

https://space.bilibili.com/523606542

前文內容

Python爬蟲新手入門教學(一):爬取豆瓣電影排行信息json

Python爬蟲新手入門教學(二):爬取小說swift

Python爬蟲新手入門教學(三):爬取鏈家二手房數據網絡

Python爬蟲新手入門教學(四):爬取前程無憂招聘信息session

Python爬蟲新手入門教學(五):爬取B站視頻彈幕ide

Python爬蟲新手入門教學(六):製做詞雲圖工具

基本開發環境

  • Python 3.6
  • Pycharm

相關模塊的使用

  • jieba
  • wordcloud

安裝Python並添加到環境變量,pip安裝須要的相關模塊便可。post

1、明確需求

選擇 <歡樂喜劇人 第七季> 爬取網友發送的彈幕信息學習

 

2、分析網頁數據

複製網頁中的彈幕,再開發者工具裏面進行搜索。

 


這裏面就有對應的彈幕數據。這個url地址有一個小特色,連接包含着 danmu 因此大膽嘗試一下,過濾搜索一下 danmu 這個關鍵詞,看一下是否有像相似的內容

 


經過連接的參數對比,能夠看到每一個url地址參數的變化

 


循環遍歷就能夠實現爬取整個視頻的彈幕了。

3、解析數據

 

在這裏想問一下,你以爲請求這個url地址給你返回的數據是什麼樣的數據?給你們三秒考慮時間。

1 …2…3…

好的,如今公佈答案了,它是一個 字符串 你沒有聽錯。若是你直接獲取 respons.json() 那你會出現報錯

 


那如何才能讓它編程json數據呢,畢竟json數據更好提取數據。

第一種方法

 

  • 正則匹配提取中間的數據部分的數據
  • 導入json模塊,字符串轉json數據
import requests import re import json import pprint url = 'https://mfm.video.qq.com/danmu?otype=json&callback=jQuery19108312825154929784_1611577043265&target_id=6416481842%26vid%3Dt0035rsjty9&session_key=30475%2C0%2C1611577043×tamp=105&_=1611577043296' headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36' } response = requests.get(url=url, headers=headers) result = re.findall('jQuery19108312825154929784_1611577043265\((.*?)\)', response.text)[0] json_data = json.loads(result) pprint.pprint(json_data)

 

第二種方法

刪除連接中的 callback=jQuery19108312825154929784_1611577043265 就能夠直接使用 response.json()

import requests import pprint url = 'https://mfm.video.qq.com/danmu?otype=json&target_id=6416481842%26vid%3Dt0035rsjty9&session_key=30475%2C0%2C1611577043×tamp=105&_=1611577043296' headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36' } response = requests.get(url=url, headers=headers) # result = re.findall('jQuery19108312825154929784_1611577043265\((.*?)\)', response.text)[0] json_data = response.json() pprint.pprint(json_data)

這樣也能夠,並且可讓代碼更加簡單。

小知識點:

pprint 是格式化輸出模塊,讓相似json數據輸出的效果更加好看

完整實現代碼

import requests for page in range(15, 150, 15): url = 'https://mfm.video.qq.com/danmu' params = { 'otype': 'json', 'target_id': '6416481842&vid=t0035rsjty9', 'session_key': '30475,0,1611577043', 'timestamp': page, '_': '1611577043296', } headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36' } response = requests.get(url=url, params=params, headers=headers) json_data = response.json() contents = json_data['comments'] for i in contents: content = i['content'] with open('喜劇人彈幕.txt', mode='a', encoding='utf-8') as f: f.write(content) f.write('\n') print(content)

代碼仍是比較簡單的。沒有什麼特別的難度。

 

相關文章
相關標籤/搜索