優雅的 Spider

Python 網頁爬蟲

Thomas Laetsch

Data Scientist, NYU

你的 Spider

import scrapy
from scrapy.crawler import CrawlerProcess

class SpiderClassName(scrapy.Spider):
    name = "spider_name"
    # the code for your spider
    ...

process = CrawlerProcess()

process.crawl(SpiderClassName)

process.start()
Python 網頁爬蟲

你的 Spider

  • 必要匯入
import scrapy
from scrapy.crawler import CrawlerProcess
  • 我們將聚焦的部分:實際的 spider
class SpiderClassName(scrapy.Spider):
    name = "spider_name"
    # the code for your spider
    ...
  • 執行 spider
# initiate a CrawlerProcess
process = CrawlerProcess()

# tell the process which spider to use
process.crawl(YourSpider)

# start the crawling process
process.start()
Python 網頁爬蟲

編織蜘蛛網

class DCspider( scrapy.Spider ):

    name = 'dc_spider'

    def start_requests( self ):
        urls = [ 'https://www.datacamp.com/courses/all' ]
        for url in urls:
            yield scrapy.Request( url = url, callback = self.parse )

    def parse( self, response ):
        # simple example: write out the html
        html_file = 'DC_courses.html'
        with open( html_file, 'wb' ) as fout:
            fout.write( response.body )
  • 需要有名為 start_requests 的函式
  • 至少需要一個解析函式處理 HTML 程式碼
Python 網頁爬蟲

一起來編織蜘蛛網

Python 網頁爬蟲

Preparing Video For Download...