あなたはスクレイプクローラーフレームワークが得意ではありませんか?クローラーフレームワークを使用してWebサイトデータを収集する簡単な使用

はじめ
にこの記事のテキストおよび画像フィルタリングネットワークは、学習、通信に使用でき、商用利用はできません。ご不明な点がございましたら、お問い合わせください。

この記事では、pythonクローラーフレームワークscrapyを使用して、Webサイトからいくつかのデータを収集します。

Pythonクローラー、データ分析、Webサイト開発、その他のケースチュートリアルビデオはオンラインで無料で視聴できます

https://www.xin3721.com/eschool/pythonxin3721/

Basic開発環境
のPython 3.6
pycharm
scrapyをインストールする方法

Pip installScrapyはcmdコマンドラインでインストールできます。ただし、一般的に、ネットワークタイムアウトが発生します。

国内の従来型ソースを切り替えて、pip install-i国内の従来型アドレスパッケージ名をインストールすることをお勧めします

例えば:

pip install -ihttps://mirrors.aliyun.com/pypi/simple/scrapy

一般的に使用される国内ソースエイリアスアドレス:

清华:https://pypi.tuna.tsinghua.edu.cn/simple
阿里云:http://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
华中理工大学:http://pypi.hustunique.com/
山东理工大学:http://pypi.sdutlinux.org/ 
豆瓣:http://pypi.douban.com/simple/

あなたが持っているかもしれないエラー:

Scrapyのインストール中にVC ++などのエラーが発生する場合があります。モジュールを削除するオフラインパッケージをインストールできます。

ここに写真の説明を挿入

ScrapyがWebサイトデータをクロールする方法

この記事では、Douban Movie Top250のデータを例として使用して、データをクロールするためのスクレイプフレームワークの基本的なプロセスを説明します。

ここに写真の説明を挿入

Douban Top250のデータはあまり分析されておらず、静的なWebサイトとWebページ構造は書き込みとクロールに非常に適しているため、基本的なクローラーのケースの多くはDouban映画データとMaoyan映画データに基づいています。

Scrapyのクローラープロジェクト作成プロセス
1.クローラープロジェクトを作成します

PycharmでTerminalを選択し、LocalでPythonの基本チュートリアル入ります

かすれたstartproject +(プロジェクト名<unique>)

ここに写真の説明を挿入

2.cdでクローラープロジェクトディレクトリに切り替えます

ここに写真の説明を挿入

3.クローラーファイルを作成します

スクレイプゲンスパイダー(+クローラーファイル名<一意>)(+ドメイン名制限)

ここに写真の説明を挿入

ここに写真の説明を挿入

これで、スクレイププロジェクトの作成とクローラーファイルの作成が完了しました。

スクレイプクローラーコードの書き込み
1、settings.pyファイルでロボットプロトコルをオフにします。デフォルトはTrueです。

ここに写真の説明を挿入

2.クローラーファイルの下の開始URLを変更します

start_urls = ['https://movie.douban.com/top250?filter=']

start_urlsをDoubanNavigation URLのリンクに変更します。これは、c#チュートリアルデータをクロールする最初のページのURLアドレスです。

3.データを分析するためのビジネスロジックを作成します

クロールの内容は次のとおりです。

ここに写真の説明を挿入

douban_info.py

import scrapy


from ..items import DoubanItem




class DoubanInfoSpider(scrapy.Spider):
    name = 'douban_info'
    allowed_domains = ['douban.com']
    start_urls = ['https://movie.douban.com/top250?start=0&filter=']


    def parse(self, response):
        lis = response.css('.grid_view li')
        print(lis)
        for li in lis:
            title = li.css('.hd span:nth-child(1)::text').get()
            movie_info = li.css('.bd p::text').getall()
            info = ''.join(movie_info).strip()
            score = li.css('.rating_num::text').get()
            number = li.css('.star span:nth-child(4)::text').get()
            summary = li.css('.inq::text').get()
            print(title)
            yield DoubanItem(title=title, info=info, score=score, number=number, summary=summary)


        href = response.css('#content .next a::attr(href)').get()
        if href:
            next_url = 'https://movie.douban.com/top250' + href
            yield scrapy.Request(url=next_url, callback=self.parse)

itmes.py

import scrapy




class DoubanItem(scrapy.Item):
    # define the fields for your item here like:
    title = scrapy.Field()
    info = scrapy.Field()
    score = scrapy.Field()
    number = scrapy.Field()
    summary = scrapy.Field()

ミドルウェア.py

import faker




def get_cookies():
    """获取cookies的函数"""
    headers = {
    
    
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36'}


    response = requests.get(url='https://movie.douban.com/top250?start=0&filter=',
                            headers=headers)
    return response.cookies.get_dict()




def get_proxies():
    """代理请求的函数"""
    proxy_data = requests.get(url='http://127.0.0.1:5000/get/').json()
    return proxy_data['proxy']




class HeadersDownloaderMiddleware:
    """headers中间件"""


    def process_request(self, request, spider):
        # 可以拿到请求体
        fake = faker.Faker()
        # request.headers  拿到请求头, 请求头是一个字典
        request.headers.update(
            {
    
    
                'user-agent': fake.user_agent(),
            }
        )
        return None


class CookieDownloaderMiddleware:
    """cookie中间件"""


    def process_request(self, request, spider):
        # request.cookies 设置请求的cookies, 是字典
        # get_cookies()  调用获取cookies的方法
        request.cookies.update(get_cookies())
        return None


class ProxyDownloaderMiddleware:
    """代理中间件"""


    def process_request(self, request, spider):
        # 获取请求的 meta , 字典
        request.meta['proxy'] = get_proxies()
        return None

pipes.py

import csv




class DoubanPipeline:
    def __init__(self):
        self.file = open('douban.csv', mode='a', encoding='utf-8', newline='')
        self.csv_file = csv.DictWriter(self.file, fieldnames=['title', 'info', 'score', 'number', 'summary'])
        self.csv_file.writeheader()


    def process_item(self, item, spider):
        dit = dict(item)
        dit['info'] = dit['info'].replace('\n', "").strip()
        self.csv_file.writerow(dit)
        return item




    def spider_closed(self, spider) -> None:
        self.file.close()

settings.py

# Scrapy settings for douban 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 = 'douban'


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




# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'douban (+http://www.yourdomain.com)'


# Obey robots.txt rules
ROBOTSTXT_OBEY = False


# 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 = {
    
    
#    'douban.middlewares.DoubanSpiderMiddleware': 543,
# }


# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
DOWNLOADER_MIDDLEWARES = {
    
    
   'douban.middlewares.HeadersDownloaderMiddleware': 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 = {
    
    
   'douban.pipelines.DoubanPipeline': 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'

4.クローラーvb.netチュートリアル
プログラムを実行します

ここに写真の説明を挿入

コマンドscrapycrawl + crawlerファイル名を入力します

ここに写真の説明を挿入

ここに写真の説明を挿入

おすすめ

転載: blog.csdn.net/chinaherolts2008/article/details/112911997