你被 `href` 了
在前一個練習中,你建立了一個 CSS 定位字串,用來選取所有屬於類別 "course-block" 的 div 元素之子層超連結(a 元素)。在這裡,我們已經建立了一個名為 course_as 的 SelectorList,其中包含那些超連結子元素。
現在,請你在下方補上空白,從這些元素擷取 href 屬性的值。這又是一個串接(chaining)的例子,就像我們在前一個練習看到的那樣。
重點是:我們可以把 css 和 xpath 這兩個方法的呼叫串接起來,甚至組合使用!若使用再一次呼叫 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( ____ )