A Classy Spider

Web Scraping in Python

Thomas Laetsch

Data Scientist, NYU

Your 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()
Web Scraping in Python

Your Spider

  • Required imports
import scrapy
from scrapy.crawler import CrawlerProcess
  • The part we will focus on: the actual spider
class SpiderClassName(scrapy.Spider):
    name = "spider_name"
    # the code for your spider
    ...
  • Running the spider
# initiate a CrawlerProcess
process = CrawlerProcess()

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

# start the crawling process
process.start()
Web Scraping in Python

Weaving the 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 )
  • Need to have a function called start_requests
  • Need to have at least one parser function to handle the HTML code
Web Scraping in Python

We'll Weave the Web Together

Web Scraping in Python

Preparing Video For Download...