您已被 `href` 住
在之前的练习中,您创建了一个 CSS 定位器字符串,用于选择所有属于类名 "course-block" 的 div 元素的超链接(a 元素)子元素。这里我们已经创建了一个名为 course_as 的 SelectorList,其中包含了这些超链接子元素。
现在,请您在下方填空,从这些元素中提取 href 属性的值。这又是一个链式选择的例子,就像我们在之前的练习中看到的那样。
这里的要点是,您可以把 css 和 xpath 方法的调用串联起来,甚至组合使用!为了把您引导到正确的方向,我们提供了当继续用 css 方法进行链式调用时的解法。
本练习是课程的一部分
Python Web 爬取
练习说明
- 使用字符串
html作为文本输入,创建Selector对象sel。 - 将变量
hrefs_from_xpath赋值为从course_as中元素提取到的href属性值。您的解答应与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( ____ )