캡스톤

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()

Python으로 하는 웹 스크레이핑

프런트 페이지 파싱

    def parse_front( self, response ):

# 코스 블록 선택 course_blocks = response.css( 'div.course-block' )
# 코스 링크로 이동 course_links = course_blocks.xpath( './a/@href' )
# 링크 추출(문자열 리스트) links_to_follow = course_links.extract()
# 링크를 따라 다음 파서 호출 for url in links_to_follow: yield response.follow( url = url, callback = self.parse_pages )
Python으로 하는 웹 스크레이핑

코스 페이지 파싱

def parse_pages( self, response ):

# 코스 제목 텍스트 선택 crs_title = response.xpath('//h1[contains(@class,"title")]/text()')
# 코스 제목 추출 및 정리 crs_title_ext = crs_title.extract_first().strip()
# 챕터 제목 텍스트 선택 ch_titles = response.css( 'h4.chapter__title::text' )
# 챕터 제목 추출 및 정리 ch_titles_ext = [t.strip() for t in ch_titles.extract()]
# 딕셔너리에 저장 dc_dict[ crs_title_ext ] = ch_titles_ext
Python으로 하는 웹 스크레이핑

이제 Weave를 사용할 시간입니다

Python으로 하는 웹 스크레이핑

Preparing Video For Download...