优雅的爬虫

Python Web 爬取

Thomas Laetsch

Data Scientist, NYU

您的爬虫

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 Web 爬取

您的爬虫

  • 必需的导入
import scrapy
from scrapy.crawler import CrawlerProcess
  • 我们将关注:实际的爬虫
class SpiderClassName(scrapy.Spider):
    name = "spider_name"
    # the code for your spider
    ...
  • 运行爬虫
# initiate a CrawlerProcess
process = CrawlerProcess()

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

# start the crawling process
process.start()
Python Web 爬取

织网

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 Web 爬取

一起织网

Python Web 爬取

Preparing Video For Download...