Web Scraping in Python
Thomas Laetsch
Data Scientist, NYU
import scrapy
from scrapy.crawler import CrawlerProcess
class DC_Chapter_Spider(scrapy.Spider):
name = "dc_chapter_spider"
def start_requests( self ):
url = 'https://www.datacamp.com/courses/all'
yield scrapy.Request( url = url,
callback = self.parse_front )
def parse_front( self, response ):
## Code to parse the front courses page
def parse_pages( self, response ):
## Code to parse course pages
## Fill in dc_dict here
dc_dict = dict()
process = CrawlerProcess()
process.crawl(DC_Chapter_Spider)
process.start()
def parse_front( self, response ):# Fokussiere die Kurs-Blöcke course_blocks = response.css( 'div.course-block' )# Gehe zu den Kurslinks course_links = course_blocks.xpath( './a/@href' )# Extrahiere die Links (als Liste von Strings) links_to_follow = course_links.extract()# Folge den Links zum nächsten Parser for url in links_to_follow: yield response.follow( url = url, callback = self.parse_pages )
def parse_pages( self, response ):# Greife auf den Kurstitel-Text zu crs_title = response.xpath('//h1[contains(@class,"title")]/text()')# Extrahiere und bereinige den Kurstitel-Text crs_title_ext = crs_title.extract_first().strip()# Greife auf die Kapitelüberschriften zu ch_titles = response.css( 'h4.chapter__title::text' )# Extrahiere und bereinige die Kapitelüberschriften ch_titles_ext = [t.strip() for t in ch_titles.extract()]# Speichere das in unserem Dictionary dc_dict[ crs_title_ext ] = ch_titles_ext
Web Scraping in Python