开始使用免费开始使用

您已被 `href` 住

在之前的练习中,您创建了一个 CSS 定位器字符串,用于选择所有属于类名 "course-block"div 元素的超链接(a 元素)子元素。这里我们已经创建了一个名为 course_asSelectorList,其中包含了这些超链接子元素。

现在,请您在下方填空,从这些元素中提取 href 属性的值。这又是一个链式选择的例子,就像我们在之前的练习中看到的那样。

这里的要点是,您可以把 cssxpath 方法的调用串联起来,甚至组合使用!为了把您引导到正确的方向,我们提供了当继续用 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( ____ )
编辑并运行代码