In this Article
想在提升网页抓取效率的同时避开反机器人系统,离不开合适的抓取工具。Scrapy 是最常用的工具之一。继续阅读,了解它为何值得关注,以及如何高效使用它。
什么是 Scrapy,它能为你带来哪些优势?
Scrapy 是一个开源的 Python 网页爬虫框架。它广受欢迎并非没有原因,主要优势包括:
- 可同时处理多个请求,从而缩短网页抓取时间
- 代码维护负担小
- 适合大规模项目
- 支持自定义请求和响应的处理方式,例如轮换 User-Agent、设置重试机制及管理代理
- 能很好地适配大量使用 JavaScript 的网站,并提供请求延迟和自动限速等功能,避免给服务器带来过高负载
- 内置数据处理管道,可将数据提取并存储为 JSON、CSV、XML 等多种格式
- 附带 CSS 选择器和 XPath 表达式,可让你精准提取所需的 HTML 元素
要了解 Scrapy 的全部功能,请访问其 官方文档。在本文中,我们将重点介绍如何使用 Scrapy。我们会访问我们的 博客,抓取所有文章标题,向你展示这个工具如何工作。
网页抓取可能触发封禁,因此将爬虫工具与代理搭配使用并不罕见。本教程将介绍如何安装和配置 Scrapy,以及如何设置代理。
准备工作
开始之前,请确保你拥有所有必要的程序和工具。本教程需要:
- Visual Studio Code (或任何支持 Python 的 IDE)
- Python (本例中为版本 3.10.0)
- pip (我们使用版本 25.0.1)
你可以在 这里 下载 VS Code,并从其 官方网站安装 Python。如果你没有 pip (它会自动包含在 Python 版本 3.4 及更高版本中),请打开记事本,并将此代码保存到名为 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")
然后,打开命令提示符并进入保存该文件的文件夹:
cd path/to/your/file
例如,我们将文件保存在 Documents 文件夹中,因此命令如下:cd/Documents.
之后,运行以下命令:
python get-pip.py
要检查 pip 是否正常工作,请使用此命令:
pip --version
现在一切准备就绪,可以开始了。
安装 Scrapy 并启动项目
首先,我们需要安装 Scrapy。为此,请打开命令提示符 (也可以在 VS Code 终端中完成),并运行以下命令:
pip install Scrapy
注意:如果已安装所有必需工具,但在 VS Code 终端中仍看到 “The term pip isn’t recognized as a name of cmdlet, function, script file, or operable program” 这条提示或其他错误,请尝试调整 VS Code 的设置。进入 Terminal>Integrated: Default Profile (可以在搜索栏中输入 terminal integrated),将默认配置文件改为命令提示符,然后重启 VS Code,使新设置生效。
要启动项目,请在 VS Code 终端中进入你的项目文件夹。本例中,该文件夹名为 Project S,位于 Documents 文件夹中,因此输入:cd Documents/Project S。
然后输入以下命令:
scrapy startproject your_project_name
请将 your_project_name替换为实际的项目名称。例如,我们使用 dataimpulse_blog。
接下来,进入项目文件夹:
cd your_project_name
进入该目录后,使用以下命令创建一个爬虫:
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)
在这里,你需要定义要抓取的页面和要收集的数据,本例中为标题。你还需要修改 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的格式填写你的实际凭据。要获取这些凭据,请在 DataImpulse 仪表盘中进入相应的代理套餐。别忘了通过右下角的按钮更改代理格式。如果遇到困难,请参考我们的 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"
在这里,你可以启用中间件,并调整缓存、Cookie、数据处理管道等其他参数。
现在进入最重要的步骤。打开终端并输入 cd ,确认你位于项目根目录。(dataimpulse_blog 是本例中的项目根目录。请查找包含 scrapy.cfg文件的文件夹,这就是根目录。)然后,使用以下命令:
scrapy crawl blog_titles -o titles.json
该命令会运行你的爬虫,并将所有结果保存到名为 titles.json的文件中。你可以直接在 VS Code 中打开该文件查看结果。以下是我们得到的内容:
至此就完成了。正如你所见,Scrapy 很容易上手。你可以根据需要调整细节,并借助代理获得更好的效果。当然,代理的选择同样重要。DataImpulse 采用按量付费模式,提供来源合规的住宅代理、数据中心代理和移动代理。你可以针对不同需求使用已加入白名单的 IP,同时控制成本。点击 “立即试用” 按钮,或发送邮件至 [email protected]。


