scrapy爬取抖音視頻

# -*- coding: utf-8 -*-
import scrapy
from douyin.items import DouyinItem
import json
import jsonpath  # jsonpath是用來方便解析大點的json文件的,用法大家百度下,挺簡單的


class DySpider(scrapy.Spider):
    name = 'DY'

    # start_urls列表實際是調用start_requests函數來處理每個url的,這裏我們重寫下自己的start_requests
    def start_requests(self):

        # 這是抖音的一個接口,每次請求這個url將會隨機返回20條左右的抖音視頻信息,count控制返回信息的多少,貌似25就是最大了。我們循環訪問這個接口抓取數據
        url = "https://aweme.snssdk.com/aweme/v1/feed/?type=0&max_cursor=0&min_cursor=0&count=25&aid=1128"

        # 這裏循環爬取10次,dont_filter設置爲True,表示不過濾重複url。因爲我們每次都是請求同一個url,不設置dont_filter默認位False,只能爬取一次
        for i in range(1, 10):
            yield scrapy.Request(url, dont_filter=True)

    def parse(self, response):
        json_response = json.loads(response.body_as_unicode())

        # 找出返回文件中所有aweme_list下的文件,也就是抖音的視頻信息列表,然後循環解析每一個視頻信息,video_info就是1個抖音視頻的所有信息
        aweme_list = jsonpath.jsonpath(json_response, "$..aweme_list")
        for aweme in aweme_list:
            for video_info in aweme:

                # digg_count是點贊數,篩選出點贊數大於10w的視頻進行解析
                digg_count = video_info["statistics"]["digg_count"]
                if int(digg_count) > 10 * 10000:

                    # 先找出aweme_id,aweme_id好像就是每個視頻的唯一標識,我們這裏要把aweme_id傳入下面的comment_url這個接口爬取評論信息,
                    aweme_id = jsonpath.jsonpath(video_info, "$.statistics.aweme_id")
                    comment_url = "https://aweme.snssdk.com/aweme/v1/comment/list/?aweme_id={}&cursor=0&count=15&aid=1128".format(
                        aweme_id[0])

                    # 訪問comment_url這個接口爬取每個視頻的評論信息,調用parse_info函數解析,meta表示將video_info中的信息傳遞給parse_info函數
                    yield scrapy.Request(comment_url, callback=self.parse_info, meta={"video_info": video_info})
                else:
                    continue

    def parse_info(self, response):
        video_info = response.meta["video_info"]  # 接收上面parse函數傳過來的video_info信息

        # 這裏只找出評論內容和評論點贊數,以列表形式返回
        comment_json = json.loads(response.body_as_unicode())
        comments = comment_json["comments"]
        comment_list = []
        for comment in comments:
            text = jsonpath.jsonpath(comment, '$..text')  # 評論內容
            digg_count = jsonpath.jsonpath(comment, '$..digg_count')  # 評論點贊數
            comment_list.append(text + digg_count)  # text+digg_count是個列表,形如["小姐姐好漂亮",1888]

        # 將每個抖音視頻所有的信息傳給init_item
        item = self.init_item(video_info, comment_list)
        yield item

    def init_item(self, video_info, comment_list):
        item = DouyinItem()

        # 作者id
        item["author_user_id"] = video_info["author_user_id"]

        # 視頻aweme_id
        item["aweme_id"] = video_info["statistics"]["aweme_id"]

        # 視頻描述
        item["video_desc"] = video_info["desc"]

        # 點贊數
        item["digg_count"] = video_info["statistics"]["digg_count"]

        # 分享數
        item["share_count"] = video_info["statistics"]["share_count"]

        # 評論數
        item["comment_count"] = video_info["statistics"]["comment_count"]

        # 評論列表
        item["comment_list"] = comment_list

        # 分享鏈接
        item["share_url"] = video_info["share_url"]

        # 封面圖鏈接列表,這裏只取一個
        item["origin_cover"] = video_info["video"]["origin_cover"]["url_list"][0]

        # 視頻播放地址列表,這裏只取一個並去掉多餘參數
        item["play_addr"] = video_info["video"]["play_addr"]["url_list"][0].split("&line")[0]

        # 視頻下載地址列表,這裏只取一個並去掉多餘參數
        download_addr = video_info["video"]["download_addr"]["url_list"][0].split("&line")[0]
        item["download_addr"] = download_addr

        return item
# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# https://docs.scrapy.org/en/latest/topics/items.html

import scrapy


class DouyinItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    author_user_id = scrapy.Field()
    video_desc = scrapy.Field()
    aweme_id = scrapy.Field()
    play_addr = scrapy.Field()
    download_addr = scrapy.Field()
    origin_cover = scrapy.Field()
    comment_info = scrapy.Field()
    comment_list = scrapy.Field()
    digg_count = scrapy.Field()
    comment_count = scrapy.Field()
    share_count = scrapy.Field()
    share_url = scrapy.Field()
# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
from pymongo import MongoClient


class DouyinPipeline(object):

    def process_item(self, item, spider):
        client = MongoClient(host="127.0.0.1", port=27017)
        db = client['DY']
        col = db['douyin']
        col.insert_one(dict(item))
        return item
# -*- coding: utf-8 -*-

# Scrapy settings for douyin project
#
# For simplicity, this file contains only settings considered important or
# commonly used. You can find more settings consulting the documentation:
#
#     https://docs.scrapy.org/en/latest/topics/settings.html
#     https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#     https://docs.scrapy.org/en/latest/topics/spider-middleware.html

BOT_NAME = 'douyin'

SPIDER_MODULES = ['douyin.spiders']
NEWSPIDER_MODULE = 'douyin.spiders'


# Crawl responsibly by identifying yourself (and your website) on the user-agent
USER_AGENT = 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) Mobile/14G60 MicroMessenger/6.5.18 NetType/WIFI Language/en'

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

# 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://docs.scrapy.org/en/latest/topics/settings.html#download-delay
# See also autothrottle settings and docs
#DOWNLOAD_DELAY = 3
# 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

# Disable Telnet Console (enabled by default)
#TELNETCONSOLE_ENABLED = False

# Override the default request headers:
#DEFAULT_REQUEST_HEADERS = {
#   'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
#   'Accept-Language': 'en',
#}

# Enable or disable spider middlewares
# See https://docs.scrapy.org/en/latest/topics/spider-middleware.html
#SPIDER_MIDDLEWARES = {
#    'douyin.middlewares.DouyinSpiderMiddleware': 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    'douyin.middlewares.DouyinDownloaderMiddleware': 543,
#}

# Enable or disable extensions
# See https://docs.scrapy.org/en/latest/topics/extensions.html
#EXTENSIONS = {
#    'scrapy.extensions.telnet.TelnetConsole': None,
#}

# Configure item pipelines
# See https://docs.scrapy.org/en/latest/topics/item-pipeline.html
ITEM_PIPELINES = {
   'douyin.pipelines.DouyinPipeline': 300,
}

# Enable and configure the AutoThrottle extension (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/autothrottle.html
#AUTOTHROTTLE_ENABLED = True
# The initial download delay
#AUTOTHROTTLE_START_DELAY = 5
# The maximum download delay to be set in case of high latencies
#AUTOTHROTTLE_MAX_DELAY = 60
# The average number of requests Scrapy should be sending in parallel to
# each remote server
#AUTOTHROTTLE_TARGET_CONCURRENCY = 1.0
# Enable showing throttling stats for every response received:
#AUTOTHROTTLE_DEBUG = False

# Enable and configure HTTP caching (disabled by default)
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html#httpcache-middleware-settings
#HTTPCACHE_ENABLED = True
#HTTPCACHE_EXPIRATION_SECS = 0
#HTTPCACHE_DIR = 'httpcache'
#HTTPCACHE_IGNORE_HTTP_CODES = []
#HTTPCACHE_STORAGE = 'scrapy.extensions.httpcache.FilesystemCacheStorage'

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章