開始使用免費開始

筆名

在這個練習中,我們已經為你建立了一個 spider 類別。完成後,它會從縮短版的 DataCamp 課程目錄中擷取作者名稱。縮短版的 URL 已儲存在變數 url_short 中。你的工作是在 spider 的 parse 方法中建立擷取後的作者名稱清單。

有兩件事你需要知道:

  • 你會在這裡使用 response 物件與 css 方法。
  • 課程作者名稱定義於屬於 class course-block__author-name 的段落 p 元素中的文字

你可以使用我們為你建立的函式 inspect_spider() 檢視 spider——它會列印出你找到的作者名稱!

注意:本章此題與後續練習可能需要一些時間載入。

本練習屬於課程

Python 網頁爬蟲

檢視課程

練習說明

  • parse 方法中填入必要的引數,讓它在 start_requests 方法呼叫時能依需求運作。
  • parse 方法中建立變數 author_names,其內容為字串清單,透過從屬於 class course-block__author-name 的段落元素中抽取文字而得。

動手互動練習

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

# Import the scrapy library
import scrapy

# Create the Spider class
class DCspider( scrapy.Spider ):
  name = 'dcspider'
  # start_requests method
  def start_requests( self ):
    yield scrapy.Request( url = url_short, callback = self.parse )
  # parse method
  def parse( ____ ):
    # Create an extracted list of course author names
    ____
    # Here we will just return the list of Authors
    return author_names
  
# Inspect the spider
inspect_spider( DCspider )
編輯並執行程式碼