DataCamp 설명
이전 연습 문제와 마찬가지로, 여기의 코드는 전체 웹 크롤링 스파이더를 다루기 때문에 길어요! 하지만 코드 길이에 겁먹지 마세요. 이제 스파이더가 어떻게 동작하는지 잘 이해하고 있으니, 여기에서 요청드리는 간단한 작업은 충분히 해내실 수 있어요.
이전 연습 문제처럼, 스파이더의 출력을 미리 볼 수 있는 previewCourses 함수를 만들어 두었어요. 코드를 실행한 뒤 dc_dict 딕셔너리를 직접 탐색하셔도 됩니다.
이번 연습에서는 강좌 설명 텍스트로 바로 가는 CSS Locator 문자열을 만들어 주세요. 알아두셔야 할 점은 강좌 페이지에서 강좌 설명 텍스트가 클래스 course__description(밑줄 두 개)에 속한 단락 요소 p 안에 있다는 것뿐이에요.
이 연습은 강의의 일부입니다
Python으로 하는 웹 스크레이핑
연습 안내
- 아래
parse_pages메서드의 빈칸 한 곳을, 클래스course__description에 속한 단락 요소p내부의 텍스트를 가리키는 CSS Locator 문자열로 채워 주세요.
NOTE: "코드 실행"을 누른 경우, 다시 성공적으로 "코드 실행"을 사용하려면 반드시 "샘플 코드로 초기화"를 해 주세요!!
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Import scrapy
import scrapy
# Import the CrawlerProcess: for running the spider
from scrapy.crawler import CrawlerProcess
# Create the Spider class
class DC_Description_Spider(scrapy.Spider):
name = "dc_chapter_spider"
# start_requests method
def start_requests(self):
yield scrapy.Request(url = url_short,
callback = self.parse_front)
# First parsing method
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)
# Second parsing method
def parse_pages(self, response):
# Create a SelectorList of the course titles text
crs_title = response.xpath('//h1[contains(@class,"title")]/text()')
# Extract the text and strip it clean
crs_title_ext = crs_title.extract_first().strip()
# Create a SelectorList of course descriptions text
crs_descr = response.css( ____ )
# Extract the text and strip it clean
crs_descr_ext = crs_descr.extract_first().strip()
# Fill in the dictionary
dc_dict[crs_title_ext] = crs_descr_ext
# Initialize the dictionary **outside** of the Spider class
dc_dict = dict()
# Run the Spider
process = CrawlerProcess()
process.crawl(DC_Description_Spider)
process.start()
# Print a preview of courses
previewCourses(dc_dict)