開始使用免費開始

DataCamp 課程描述

和上一題一樣,這裡的程式碼很長,因為你正在操作整個網路爬蟲 spider!不過別被程式碼量嚇到。你現在已經掌握 spider 的運作方式,完全有能力完成這裡的簡單任務。

同樣地,我們建立了一個 previewCourses 函式,讓你可以預覽 spider 的輸出。不過在執行程式碼之後,你也可以直接查看字典 dc_dict

本題要你建立一個 CSS 定位器字串,直接選到課程描述的文字。你只需要知道,在課程頁面中,課程描述文字位於屬於 class course__description(兩個底線)的段落 p 元素裡。

本練習屬於課程

Python 網頁爬蟲

檢視課程

練習說明

  • parse_pages 方法中的唯一空格,填入一個 CSS 定位器字串,能夠選取屬於 class course__description 的段落 p 元素中的文字。

NOTE: 如果你按下 Run Code,再次成功使用 Run Code 前必須先使用 Reset to Sample Code!!

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# 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)
編輯並執行程式碼