開始使用免費開始

動手執行

在上一個課程中,我們完成了一個完整的網頁爬蟲,用來從 DataCamp 的課程目錄中抓取每門課的資訊。不過,課程在講完解析方法後就收尾了,少了點高潮,因為我們沒有在完成後實際玩玩看這段程式碼。

這個練習就是要補上這一塊!

接下來這個練習和下一個練習中,你會看到的程式碼很長,因為它就是我們在課程裡一步步建立的整個 spider!不過別被嚇到!這兩個練習的目的,是給你一個「非常」簡單就能完成的任務,藉此鼓勵你去閱讀並執行這個 spider 的程式碼。這樣一來,即使程式碼很長,你也能掌握它的結構與用法!

本練習屬於課程

Python 網頁爬蟲

檢視課程

練習說明

  • parse_pages 方法的結尾填入唯一一個空格,將章節標題指定給字典,該字典以對應的課程標題作為鍵。

注意:如果你按下 Run Code,你必須使用 Reset to sample code 才能再次成功使用 Run Code

動手互動練習

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

# Import scrapy
import scrapy

# Import the CrawlerProcess: for running the spider
from scrapy.crawler import CrawlerProcess

# Create the Spider class
class DC_Chapter_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):
    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 ] = ____

# Initialize the dictionary **outside** of the Spider class
dc_dict = dict()

# Run the Spider
process = CrawlerProcess()
process.crawl(DC_Chapter_Spider)
process.start()

# Print a preview of courses
previewCourses(dc_dict)
編輯並執行程式碼