亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

溫馨提示×

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

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Python爬蟲入門【19】: B站博人傳評論數據抓取 scrapy

發布時間:2020-07-22 00:41:20 來源:網絡 閱讀:1029 作者:學Python派森 欄目:編程語言

1. B站博人傳評論數據爬取簡介

今天想了半天不知道抓啥,去B站看跳舞的×××姐,忽然看到了評論,那就抓取一下B站的評論數據,視頻動畫那么多,也不知道抓取哪個,選了一個博人傳跟火影相關的,抓取看看。網址: https://www.bilibili.com/bangumi/media/md5978/?from=search&seid=16013388136765436883#short
在這個網頁看到了18560條短評,數據量也不大,抓取看看,使用的還是scrapy。

Python爬蟲入門【19】: B站博人傳評論數據抓取 scrapy

Python爬蟲入門【19】: B站博人傳評論數據抓取 scrapy

2. B站博人傳評論數據案例---獲取鏈接

從開發者工具中你能輕易的得到如下鏈接,有鏈接之后就好辦了,如何創建項目就不在啰嗦了,我們直接進入主題。

Python爬蟲入門【19】: B站博人傳評論數據抓取 scrapy

我在代碼中的parse函數中,設定了兩個yield一個用來返回items 一個用來返回requests
然后實現一個新的功能,每次訪問切換UA,這個點我們需要使用到中間件技術。


class BorenSpider(scrapy.Spider):
    BASE_URL = "https://bangumi.bilibili.com/review/web_api/short/list?media_id=5978&folded=0&page_size=20&sort=0&cursor={}"
    name = 'Boren'
    allowed_domains = ['bangumi.bilibili.com']

    start_urls = [BASE_URL.format("76742479839522")]

    def parse(self, response):
        print(response.url)
        resdata = json.loads(response.body_as_unicode())

        if resdata["code"] == 0:
            # 獲取最后一個數據
            if len(resdata["result"]["list"]) > 0:
                data = resdata["result"]["list"]
                cursor = data[-1]["cursor"]
                for one in data:
                    item = BorenzhuanItem()

                    item["author"]  = one["author"]["uname"]
                    item["content"] = one["content"]
                    item["ctime"] = one["ctime"]
                    item["disliked"] = one["disliked"]
                    item["liked"] = one["liked"]
                    item["likes"] = one["likes"]
                    item["user_season"] = one["user_season"]["last_ep_index"] if "user_season" in one else ""
                    item["score"] = one["user_rating"]["score"]
                    yield item

            yield scrapy.Request(self.BASE_URL.format(cursor),callback=self.parse)
Python資源分享qun 784758214 ,內有安裝包,PDF,學習視頻,這里是Python學習者的聚集地,零基礎,進階,都歡迎

3. B站博人傳評論數據案例---實現隨機UA

第一步, 在settings文件中添加一些UserAgent,我從互聯網找了一些

USER_AGENT_LIST=[
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1",
    "Mozilla/5.0 (X11; CrOS i686 2268.111.0) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.57 Safari/536.11",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1092.0 Safari/536.6",
    "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.6 (KHTML, like Gecko) Chrome/20.0.1090.0 Safari/536.6",
    "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/19.77.34.5 Safari/537.1",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.9 Safari/536.5",
    "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.36 Safari/536.5",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
    "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1063.0 Safari/536.3",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)",
    "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1062.0 Safari/536.3",
    "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)",
    "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
    "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.1 Safari/536.3",
    "Mozilla/5.0 (Windows NT 6.2) AppleWebKit/536.3 (KHTML, like Gecko) Chrome/19.0.1061.0 Safari/536.3",
    "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24",
    "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/535.24 (KHTML, like Gecko) Chrome/19.0.1055.1 Safari/535.24"
]

第二步,在settings文件中設置 “DOWNLOADER_MIDDLEWARES”

# Enable or disable downloader middlewares
# See https://doc.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
   #'borenzhuan.middlewares.BorenzhuanDownloaderMiddleware': 543,
    'borenzhuan.middlewares.RandomUserAgentMiddleware': 400,
}

第三步,在 middlewares.py 文件中導入 settings模塊中的 USER_AGENT_LIST 方法

from borenzhuan.settings import USER_AGENT_LIST # 導入中間件
import random

class RandomUserAgentMiddleware(object):
    def process_request(self, request, spider):
        rand_use  = random.choice(USER_AGENT_LIST)
        if rand_use:
            request.headers.setdefault('User-Agent', rand_use)

好了,隨機的UA已經實現,你可以在parse函數中編寫如下代碼進行測試

print(response.request.headers)

4. B站博人傳評論數據----完善item

這個操作相對簡單,這些數據就是我們要保存的數據了。!

   author = scrapy.Field()
    content = scrapy.Field()
    ctime = scrapy.Field()
    disliked = scrapy.Field()
    liked = scrapy.Field()
    likes = scrapy.Field()
    score = scrapy.Field()
    user_season = scrapy.Field()

5. B站博人傳評論數據案例---提高爬取速度

在settings.py中設置如下參數:


# Configure maximum concurrent requests performed by Scrapy (default: 16)
CONCURRENT_REQUESTS = 32
# Configure a delay for requests for the same website (default: 0)
# See https://doc.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
DOWNLOAD_DELAY = 1
# The download delay setting will honor only one of:
CONCURRENT_REQUESTS_PER_DOMAIN = 16
CONCURRENT_REQUESTS_PER_IP = 16
# Disable cookies (enabled by default)
COOKIES_ENABLED = False

解釋說明

一、降低下載延遲

DOWNLOAD_DELAY = 0

將下載延遲設為0,這時需要相應的防ban措施,一般使用user agent輪轉,構建user agent池,輪流選擇其中之一來作為user agent。

二、多線程

CONCURRENT_REQUESTS = 32
CONCURRENT_REQUESTS_PER_DOMAIN = 16
CONCURRENT_REQUESTS_PER_IP = 16

scrapy網絡請求是基于Twisted,而Twisted默認支持多線程,而且scrapy默認也是通過多線程請求的,并且支持多核CPU的并發,我們通過一些設置提高scrapy的并發數可以提高爬取速度。

三、禁用cookies

COOKIES_ENABLED = False

6. B站博人傳評論數據案例---保存數據

最后在pipelines.py 文件中,編寫保存代碼即可

import os
import csv

class BorenzhuanPipeline(object):

    def __init__(self):
        store_file = os.path.dirname(__file__)+'/spiders/bore.csv'
        self.file = open(store_file,"a+",newline="",encoding="utf-8")
        self.writer = csv.writer(self.file)

    def process_item(self, item, spider):
        try:

            self.writer.writerow((
                item["author"],
                item["content"],
                item["ctime"],
                item["disliked"],
                item["liked"],
                item["likes"],
                item["score"],
                item["user_season"]
            ))

        except Exception as e:
            print(e.args)

        def close_spider(self, spider):
            self.file.close()
Python資源分享qun 784758214 ,內有安裝包,PDF,學習視頻,這里是Python學習者的聚集地,零基礎,進階,都歡迎

運行代碼之后,發現過了一會報錯了

Python爬蟲入門【19】: B站博人傳評論數據抓取 scrapy

去看了一眼,原來是數據爬取完畢<sub>!!!</sub>

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

古交市| 个旧市| 乌海市| 湾仔区| 磴口县| 文水县| 府谷县| 达孜县| 修水县| 阳城县| 遂溪县| 集贤县| 普陀区| 锦屏县| 游戏| 伊川县| 乐至县| 宝清县| 上栗县| 隆昌县| 吴桥县| 富裕县| 玉环县| 无棣县| 武汉市| 湛江市| 慈利县| 玉林市| 虞城县| 偃师市| 姜堰市| 庆安县| 徐州市| 青神县| 沂源县| 沭阳县| 萨迦县| 郎溪县| 灵武市| 宜都市| 凤阳县|