DI logo and Scrapy logo

ความจำเป็นในการเร่งความเร็ว web scraping พร้อมหลีกเลี่ยงการกระตุ้นระบบป้องกันบอต ทำให้ต้องใช้เครื่องมือสำหรับ web scraping ที่ใช้งานได้จริง Scrapy เป็นหนึ่งในเครื่องมือที่ใช้กันแพร่หลายที่สุด อ่านต่อเพื่อดูว่าทำไมจึงคุ้มค่าที่จะสนใจ และจะใช้อย่างมีประสิทธิภาพได้อย่างไร

Scrapy คืออะไร และมีข้อดีอะไรบ้าง?

Scrapy คือเฟรมเวิร์ก Python แบบโอเพนซอร์สสำหรับรวบรวมข้อมูลจากเว็บ ที่ได้รับความนิยมก็มีเหตุผล เพราะมีข้อดีดังนี้:

  • รองรับการจัดการคำขอหลายรายการพร้อมกัน จึงใช้เวลาทำ web scraping น้อยลง
  • ไม่จำเป็นต้องบำรุงรักษาโค้ด
  • เหมาะกับโครงการขนาดใหญ่
  • ปรับแต่งการจัดการคำขอและการตอบกลับได้ เช่น เพิ่มการสลับ user-agent จัดการการลองใหม่ และจัดการ proxy
  • ทำงานได้ดีกับเว็บไซต์ที่ใช้ JavaScript มาก และมีฟีเจอร์อย่างการหน่วงคำขอและการควบคุมความเร็วอัตโนมัติเพื่อไม่ให้เซิร์ฟเวอร์ทำงานหนักเกินไป 
  • มี item pipeline ในตัว จึงดึง จัดเก็บ และบันทึกข้อมูลได้หลายรูปแบบ เช่น JSON, CSV และ XML
  • มาพร้อม CSS selectors และ XPath expressions ช่วยให้ดึงองค์ประกอบ HTML ที่ต้องการได้อย่างแม่นยำ 

หากต้องการทำความรู้จักฟีเจอร์ทั้งหมดของ Scrapy โปรดดู เอกสารอย่างเป็นทางการ. ในบทความนี้ เราจะเน้นวิธีใช้ Scrapy โดยจะเข้าไปที่ บล็อก ของเรา แล้วดึงชื่อบทความทั้งหมดเพื่อแสดงให้เห็นว่าเครื่องมือนี้ทำงานอย่างไร 

เนื่องจาก web scraping มีความเสี่ยงที่จะถูกแบน การใช้เครื่องมือรวบรวมข้อมูลร่วมกับ proxy จึงไม่ใช่เรื่องใหม่ ในบทแนะนำนี้ เราจะแสดงวิธีติดตั้งและปรับแต่ง Scrapy รวมถึงวิธีนำ proxy มาใช้ 

การเตรียมพร้อม 

ก่อนเริ่มต้น โปรดตรวจสอบว่ามีโปรแกรมและเครื่องมือที่จำเป็นครบถ้วน สำหรับบทแนะนำนี้ ต้องใช้: 

  • Visual Studio Code (หรือ IDE อื่นที่รองรับ Python) 
  • Python (ในกรณีนี้ใช้เวอร์ชัน 3.10.0)
  • pip (เราใช้เวอร์ชัน 25.0.1)

คุณสามารถดาวน์โหลด VS Code ที่นี่ และติดตั้ง Python จาก เว็บไซต์อย่างเป็นทางการ หากไม่มี pip (ซึ่งมาพร้อม Python เวอร์ชัน 3.4 ขึ้นไปโดยอัตโนมัติ) ให้เปิด Notebook และบันทึกโค้ดนี้ลงในไฟล์ get-pip.py:


import urllib.request
import os
import sys

try:
    # download get-pip.py
    url = "https://bootstrap.pypa.io/get-pip.py"
    urllib.request.urlretrieve(url, "get-pip.py")

    # install pip
    os.system(f"{sys.executable} get-pip.py")
finally:
    # remove the script
    if os.path.exists("get-pip.py"):
        os.remove("get-pip.py")

      
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
      

จากนั้น เปิด command prompt แล้วไปยังโฟลเดอร์ที่บันทึกไฟล์ไว้:


cd path/to/your/file

      
        
      

ตัวอย่างเช่น เราบันทึกไฟล์ไว้ในโฟลเดอร์ Documents ดังนั้นคำสั่งจะเป็น cd/Documents.

หลังจากนั้น ให้รันคำสั่งต่อไปนี้:


python get-pip.py

      
        
      

เพื่อตรวจสอบว่า pip ทำงานปกติ ให้ใช้คำสั่งนี้:


pip --version

      
        
      

เมื่อเตรียมทุกอย่างพร้อมแล้ว มาเริ่มกันเลย

การติดตั้ง Scrapy และเริ่มโครงการ

ก่อนอื่น ต้องติดตั้ง Scrapy โดยเปิด command prompt (หรือทำใน terminal ของ VS Code) แล้วรันคำสั่งต่อไปนี้:


pip install Scrapy

      
        
      

หมายเหตุ: หากติดตั้งเครื่องมือที่จำเป็นครบแล้ว แต่ยังพบข้อความว่าไม่รู้จัก pip ในฐานะชื่อของ cmdlet, function, script file หรือโปรแกรมที่ใช้งานได้ หรือพบข้อผิดพลาดอื่นใน terminal ของ VS Code ให้ลองปรับการตั้งค่า VS Code ไปที่ Terminal>Integrated: Default Profile (พิมพ์ terminal integrated ในแถบค้นหาได้) เปลี่ยน default profile เป็น command prompt แล้วรีสตาร์ต VS Code เพื่อเปิดใช้การตั้งค่าใหม่

หากต้องการเริ่มโครงการ ให้ไปยังโฟลเดอร์โครงการใน terminal ของ VS Code ในกรณีนี้ โฟลเดอร์ชื่อ Project S อยู่ในโฟลเดอร์ Documents ดังนั้นจึงพิมพ์ cd Documents/Project S.

จากนั้น พิมพ์คำสั่งนี้:


scrapy startproject your_project_name

      
        
      

อย่าลืมแทนที่ your_project_name ด้วยชื่อจริง ตัวอย่างเช่น เราใช้ dataimpulse_blog

จากนั้น ไปยังโฟลเดอร์โครงการ:


cd your_project_name

      
        
      

เมื่ออยู่ในโฟลเดอร์แล้ว ให้ใช้คำสั่งนี้เพื่อสร้าง spider:


scrapy genspider your_spider_name url_domain

      
        
      

ในกรณีนี้ คำสั่งมีลักษณะดังนี้ scrapy genspider blog_titles dataimpulse.com

การปรับโค้ด

ไม่ว่าจะเปิดโฟลเดอร์โครงการใน VS Code หรือผ่าน File Explorer คุณจะเห็นไฟล์ Python หลายไฟล์อยู่ในนั้น เราต้องแก้ไขไฟล์เหล่านี้เพื่อดึงข้อมูลที่จำเป็น

ก่อนอื่น ในโฟลเดอร์ “spiders” ให้เปิด blog_titles.py แล้วแทนที่โค้ดเดิมด้วยโค้ดนี้:


import scrapy


class BlogTitlesSpider(scrapy.Spider):
    name = 'blog_titles'
    allowed_domains = ['dataimpulse.com']
    start_urls = ['https://dataimpulse.com/blog/']
    def parse(self, response):
        self.logger.info(f"Visited {response.url}")

       
        titles = response.css('h3.blog-title a::text').getall()
        for title in titles:
            yield {'title': title.strip()}

       
        next_page = response.css('a.next::attr(href)').get()
        if next_page:
            yield response.follow(next_page, callback=self.parse)

      
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
      

ตรงนี้ ให้กำหนดหน้าที่ต้องการ scrape และข้อมูลที่ต้องการรวบรวม (ในกรณีนี้คือชื่อเรื่อง) รวมทั้งแก้ไขเมธอด parse

จากนั้น เปิด middlewares.py แล้ววางโค้ดต่อไปนี้ลงไป:


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

from scrapy import signals

# useful for handling different item types with a single interface
from itemadapter import is_item, ItemAdapter


class BlogscraperSpiderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, or item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Request or item objects.
        pass
    
    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        for r in start_requests:
            yield r

    def spider_opened(self, spider):
        spider.logger.info("Spider opened: %s" % spider.name)


class BlogscraperDownloaderMiddleware:
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the downloader middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    def process_request(self, request, spider):
        # Called for each request that goes through the downloader
        # middleware.

        # Must either:
        # - return None: continue processing this request
        # - or return a Response object
        # - or return a Request object
        # - or raise IgnoreRequest: process_exception() methods of
        #   installed downloader middleware will be called
        request.meta['proxy'] = spider.settings.get('http://login:password@hostname:port')

    def process_response(self, request, response, spider):
        # Called with the response returned from the downloader.

        # Must either;
        # - return a Response object
        # - return a Request object
        # - or raise IgnoreRequest
        return response

    def process_exception(self, request, exception, spider):
        # Called when a download handler or a process_request()
        # (from other downloader middleware) raises an exception.

        # Must either:
        # - return None: continue processing this exception
        # - return a Response object: stops process_exception() chain
        # - return a Request object: stops process_exception() chain
        pass

    def spider_opened(self, spider):
        spider.logger.info("Spider opened: %s" % spider.name)

      
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
      

โปรดดูบรรทัดที่ 81 ตรงนี้ ต้องกรอกข้อมูลรับรองจริงของคุณในรูปแบบ http://login:password@hostname:port หากต้องการรับข้อมูลนี้ ให้ไปที่แผน proxy ที่ต้องการใน DataImpulse dashboard อย่าลืมเปลี่ยนรูปแบบ proxy ที่มุมขวาของปุ่ม หากมีปัญหา โปรดใช้ คู่มือการจัดการบัญชี DataImpulse.

สุดท้าย ไปที่ settings.py และตรวจสอบให้แน่ใจว่าเป็นดังนี้:


# Scrapy settings for blogscraper 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 = "dataimpulse_blog"

SPIDER_MODULES = ["dataimpulse_blog.spiders"]
NEWSPIDER_MODULE = "dataimpulse_blog.spiders"


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

# Obey robots.txt rules
ROBOTSTXT_OBEY = True

# Enable the downloader middlewares
DOWNLOADER_MIDDLEWARES = {
    'scrapy.downloadermiddlewares.httpproxy.HttpProxyMiddleware': 110,
    'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None,
    'dataimpulse_blog.middlewares.BlogscraperSpiderMiddleware': 543,  # Add your ProxyMiddleware here
}

# 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 = {
#    "blogscraper.middlewares.BlogscraperSpiderMiddleware": 543,
#}

# Enable or disable downloader middlewares
# See https://docs.scrapy.org/en/latest/topics/downloader-middleware.html
#DOWNLOADER_MIDDLEWARES = {
#    "blogscraper.middlewares.BlogscraperDownloaderMiddleware": 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 = {
#    "blogscraper.pipelines.BlogscraperPipeline": 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"

# Set settings whose default value is deprecated to a future-proof value
REQUEST_FINGERPRINTER_IMPLEMENTATION = "2.7"
TWISTED_REACTOR = "twisted.internet.asyncioreactor.AsyncioSelectorReactor"
FEED_EXPORT_ENCODING = "utf-8"

      
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
      

ตรงนี้ คุณเปิดใช้ middleware และปรับพารามิเตอร์อื่น เช่น caching, cookies, pipelines เป็นต้น

ถึงขั้นตอนสำคัญแล้ว เปิด Terminal แล้วพิมพ์ cd เพื่อตรวจสอบว่าอยู่ใน root directory ของโครงการ (ในกรณีนี้คือ dataimpulse_blog; ให้มองหาโฟลเดอร์ที่มีไฟล์ scrapy.cfg ซึ่งก็คือ root directory) จากนั้น ใช้คำสั่งต่อไปนี้:


scrapy crawl blog_titles -o titles.json

      
        
      

คำสั่งนี้จะรัน spider และบันทึกผลลัพธ์ทั้งหมดไว้ในไฟล์ชื่อ titles.json คุณตรวจสอบผลลัพธ์ได้โดยเปิดไฟล์ใน VS Code นี่คือผลลัพธ์ที่ได้:

เสร็จเรียบร้อยแล้ว ดังที่เห็น Scrapy ใช้งานง่าย คุณปรับรายละเอียดที่จำเป็นและใช้ proxy เพื่อให้ได้ผลลัพธ์ที่ดีที่สุดได้ แน่นอนว่าการเลือก proxy ก็สำคัญเช่นกัน DataImpulse มี residential proxy, datacenter และ mobile proxy ที่จัดหามาอย่างถูกต้องตามกฎหมาย ในรูปแบบการคิดค่าบริการตามการใช้งาน คุณมี IP ที่อยู่ในรายการอนุญาตสำหรับความต้องการใช้งานทั่วไปโดยไม่ทำให้งบประมาณหมด เริ่มต้นกับเราได้ด้วยการคลิกปุ่ม “ลองใช้ตอนนี้” หรือเขียนถึงเราได้ที่ [email protected].