# 常用做法
> 譯者:[OSGeo 中國](https://www.osgeo.cn/)
本節記錄使用Scrapy時的常見做法。這些內容涵蓋了許多主題,通常不屬于任何其他特定部分。
## 從腳本中運行Scrapy
你可以使用 [API](api.html#topics-api) 從腳本運行scrapy,而不是運行scrapy via的典型方式 `scrapy crawl` .
記住,scrappy構建在TwistedAsynchronicNetworkLibrary之上,所以需要在TwistedReactor中運行它。
你能用來運行 Spider 的第一個工具是 `scrapy.crawler.CrawlerProcess` . 這個類將為您啟動一個扭曲的反應器,配置日志記錄和設置關閉處理程序。這個類是所有slapy命令使用的類。
下面是一個示例,演示如何使用它運行單個 Spider 。
```py
import scrapy
from scrapy.crawler import CrawlerProcess
class MySpider(scrapy.Spider):
# Your spider definition
...
process = CrawlerProcess({
'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)'
})
process.crawl(MySpider)
process.start() # the script will block here until the crawling is finished
```
一定要檢查 `CrawlerProcess` 了解其使用細節的文檔。
如果您在一個零碎的項目中,有一些額外的幫助器可以用來導入項目中的那些組件。你可以自動輸入 Spider 的名字 `CrawlerProcess` 及使用 `get_project_settings` 得到一個 [`Settings`](api.html#scrapy.settings.Settings "scrapy.settings.Settings") 具有項目設置的實例。
下面是一個如何使用 [testspiders](https://github.com/scrapinghub/testspiders) 以項目為例。
```py
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import get_project_settings
process = CrawlerProcess(get_project_settings())
# 'followall' is the name of one of the spiders of the project.
process.crawl('followall', domain='scrapinghub.com')
process.start() # the script will block here until the crawling is finished
```
還有另一個Scrapy實用程序,它提供了對爬行過程的更多控制: `scrapy.crawler.CrawlerRunner` . 這個類是一個薄包裝器,它封裝了一些簡單的幫助器來運行多個爬行器,但是它不會以任何方式啟動或干擾現有的反應器。
使用這個類,在調度spider之后應該顯式地運行reactor。建議您使用 `CrawlerRunner` 而不是 `CrawlerProcess` 如果您的應用程序已經在使用Twisted,并且您希望在同一個反應器中運行Scrapy。
請注意, Spider 完成后,您還必須自己關閉扭曲的反應堆。這可以通過將回調添加到由 `CrawlerRunner.crawl` 方法。
下面是一個使用它的例子,以及在 `MySpider` 已完成運行。
```py
from twisted.internet import reactor
import scrapy
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
class MySpider(scrapy.Spider):
# Your spider definition
...
configure_logging({'LOG_FORMAT': '%(levelname)s: %(message)s'})
runner = CrawlerRunner()
d = runner.crawl(MySpider)
d.addBoth(lambda _: reactor.stop())
reactor.run() # the script will block here until the crawling is finished
```
參見
[Twisted Reactor Overview](https://twistedmatrix.com/documents/current/core/howto/reactor-basics.html) .
## 在同一進程中運行多個spider
默認情況下,當您運行時,scrapy為每個進程運行一個spider `scrapy crawl` . 但是,Scrapy支持使用 [internal API](api.html#topics-api) .
下面是一個同時運行多個 Spider 的示例:
```py
import scrapy
from scrapy.crawler import CrawlerProcess
class MySpider1(scrapy.Spider):
# Your first spider definition
...
class MySpider2(scrapy.Spider):
# Your second spider definition
...
process = CrawlerProcess()
process.crawl(MySpider1)
process.crawl(MySpider2)
process.start() # the script will block here until all crawling jobs are finished
```
使用相同的示例 `CrawlerRunner` :
```py
import scrapy
from twisted.internet import reactor
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
class MySpider1(scrapy.Spider):
# Your first spider definition
...
class MySpider2(scrapy.Spider):
# Your second spider definition
...
configure_logging()
runner = CrawlerRunner()
runner.crawl(MySpider1)
runner.crawl(MySpider2)
d = runner.join()
d.addBoth(lambda _: reactor.stop())
reactor.run() # the script will block here until all crawling jobs are finished
```
同樣的例子,但是通過鏈接延遲來按順序運行spider:
```py
from twisted.internet import reactor, defer
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
class MySpider1(scrapy.Spider):
# Your first spider definition
...
class MySpider2(scrapy.Spider):
# Your second spider definition
...
configure_logging()
runner = CrawlerRunner()
@defer.inlineCallbacks
def crawl():
yield runner.crawl(MySpider1)
yield runner.crawl(MySpider2)
reactor.stop()
crawl()
reactor.run() # the script will block here until the last crawl call is finished
```
參見
[從腳本中運行Scrapy](#run-from-script) .
## 分布式爬行
Scrapy不提供任何以分布式(多服務器)方式運行爬蟲的內置工具。但是,有一些分發爬行的方法,這取決于您計劃如何分發爬行。
如果您有許多 Spider ,那么分配負載的最明顯的方法就是設置許多ScrapyD實例,并將 Spider 運行分布在這些實例中。
如果您想在多臺機器上運行一個(大) Spider ,通常需要對URL進行分區,以便爬行并將它們發送到每個單獨的 Spider 。下面是一個具體的例子:
首先,準備要爬網的URL列表并將其放入單獨的文件/URL::
```py
http://somedomain.com/urls-to-crawl/spider1/part1.list
http://somedomain.com/urls-to-crawl/spider1/part2.list
http://somedomain.com/urls-to-crawl/spider1/part3.list
```
然后在3個不同的ScrapyD服務器上啟動一個 Spider 運行。 Spider 會收到一個( Spider )論點 `part` 使用要爬網的分區的編號::
```py
curl http://scrapy1.mycompany.com:6800/schedule.json -d project=myproject -d spider=spider1 -d part=1
curl http://scrapy2.mycompany.com:6800/schedule.json -d project=myproject -d spider=spider1 -d part=2
curl http://scrapy3.mycompany.com:6800/schedule.json -d project=myproject -d spider=spider1 -d part=3
```
## 避免被禁止
一些網站實施了某些措施,以防止僵尸爬行他們,不同程度的復雜度。繞開這些措施既困難又棘手,有時可能需要特殊的基礎設施。請考慮聯系 [commercial support](https://scrapy.org/support/) 如果有疑問。
以下是處理此類網站時要記住的一些提示:
* 將你的用戶代理從瀏覽器中的一個著名的池中輪換出來(用google搜索以獲得一個列表)。
* 禁用cookies(請參見 [`COOKIES_ENABLED`](downloader-middleware.html#std:setting-COOKIES_ENABLED) )因為有些網站可能會使用cookie來發現機器人行為
* 使用下載延遲(2或更高)。見 [`DOWNLOAD_DELAY`](settings.html#std:setting-DOWNLOAD_DELAY) 設置。
* 如果可能,使用 [Google cache](http://www.googleguide.com/cached_pages.html) 獲取頁面,而不是直接訪問站點
* 使用一個旋轉的IP池。例如,自由 [Tor project](https://www.torproject.org/) 或者像這樣的付費服務 [ProxyMesh](https://proxymesh.com/) . 開源替代方案是 [scrapoxy](https://scrapoxy.io/) ,可以將自己的代理附加到的超級代理。
* 使用一個在內部繞過BAN的高度分布式下載程序,這樣您就可以專注于解析干凈的頁面。這種下載器的一個例子是 [Crawlera](https://scrapinghub.com/crawlera)
如果您仍然無法阻止您的bot被禁止,請考慮聯系 [commercial support](https://scrapy.org/support/) .
- 簡介
- 第一步
- Scrapy at a glance
- 安裝指南
- Scrapy 教程
- 實例
- 基本概念
- 命令行工具
- Spider
- 選擇器
- 項目
- 項目加載器
- Scrapy shell
- 項目管道
- Feed 導出
- 請求和響應
- 鏈接提取器
- 設置
- 例外情況
- 內置服務
- Logging
- 統計數據集合
- 發送電子郵件
- 遠程登錄控制臺
- Web服務
- 解決具體問題
- 常見問題
- 調試spiders
- Spider 合約
- 常用做法
- 通用爬蟲
- 使用瀏覽器的開發人員工具進行抓取
- 調試內存泄漏
- 下載和處理文件和圖像
- 部署 Spider
- AutoThrottle 擴展
- Benchmarking
- 作業:暫停和恢復爬行
- 延伸 Scrapy
- 體系結構概述
- 下載器中間件
- Spider 中間件
- 擴展
- 核心API
- 信號
- 條目導出器
- 其余所有
- 發行說明
- 為 Scrapy 貢獻
- 版本控制和API穩定性