En klassig spindel

Webbskrapning i Python

Thomas Laetsch

Data Scientist, NYU

Din spindel

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()
Webbskrapning i Python

Din spindel

  • Nödvändiga importer
import scrapy
from scrapy.crawler import CrawlerProcess
  • Det vi fokuserar på: själva spindeln
class SpiderClassName(scrapy.Spider):
    name = "spider_name"
    # the code for your spider
    ...
  • Köra spindeln
# initiate a CrawlerProcess
process = CrawlerProcess()

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

# start the crawling process
process.start()
Webbskrapning i Python

Väva nätet

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 )
  • Måste ha en funktion med namnet start_requests
  • Måste ha minst en parserfunktion som hanterar HTML-koden
Webbskrapning i Python

Vi väver nätet tillsammans

Webbskrapning i Python

Preparing Video For Download...