DataCamp の説明文
前の演習と同様に、ここでも本格的なウェブクローリング用のスパイダーを扱うため、コードは長めです。ただし、コード量に圧倒されないでください。スパイダーの仕組みはすでに理解できていますし、ここでお願いする作業は簡単にこなせます。
前の演習と同じく、スパイダーの出力をプレビューできる関数 previewCourses を用意しています。コードを実行した後は、辞書 dc_dict を直接確認してもかまいません。
この演習では、コース説明文のテキストに直接アクセスするための CSS ロケーター文字列を作成します。コースページでは、説明文テキストはクラス course__description(アンダースコア2つ)に属する段落要素 p の中にあります。
この演習はコースの一部です
Pythonで学ぶWebスクレイピング
演習の手順
- 下の
parse_pagesメソッド内の空欄1カ所を埋め、クラスcourse__descriptionに属する段落要素p内のテキストを指す CSS ロケーター文字列を記述してください。
注意: 「コードを実行する」を押した後に再度実行する場合は、必ず「サンプルコードにリセット」を行ってから再度「コードを実行する」を押してください。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# 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)