開始使用免費開始

你被 `href` 了

在前一個練習中,你建立了一個 CSS 定位字串,用來選取所有屬於類別 "course-block"div 元素之子層超連結(a 元素)。在這裡,我們已經建立了一個名為 course_asSelectorList,其中包含那些超連結子元素。

現在,請你在下方補上空白,從這些元素擷取 href 屬性的值。這又是一個串接(chaining)的例子,就像我們在前一個練習看到的那樣。

重點是:我們可以把 cssxpath 這兩個方法的呼叫串接起來,甚至組合使用!若使用再一次呼叫 css 方法來串接,我們也提供了參考解答,幫助你往正確方向前進。

本練習屬於課程

Python 網頁爬蟲

檢視課程

練習說明

  • 以字串 html 作為文字輸入,建立 Selector 物件 sel
  • course_as 中元素的 href 屬性值指定給變數 hrefs_from_xpath。你的解答應該要與 hrefs_from_css 相同!

動手互動練習

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

from scrapy import Selector

# Create a selector object from a secret website
sel = Selector( ____ )

# Select all hyperlinks of div elements belonging to class "course-block"
course_as = sel.css( 'div.course-block > a' )

# Selecting all href attributes chaining with css
hrefs_from_css = course_as.css( '::attr(href)' )

# Selecting all href attributes chaining with xpath
hrefs_from_xpath = course_as.xpath( ____ )
編輯並執行程式碼