开始使用免费开始使用

DataCamp 课程描述

与上一个练习类似,这里的代码很长,因为您正在使用一个完整的网络爬虫(spider)!不过别被代码量吓到。您已经掌握了 spider 的工作方式,完全可以完成这里的简单任务。

和上一个练习一样,我们创建了一个函数 previewCourses,用于预览 spider 的输出。当然,您在运行代码后也可以直接查看字典 dc_dict

在本练习中,要求您编写一个 CSS 定位器字符串,直接定位到课程描述的文本。您只需要知道:在课程页面上,课程描述文本位于一个段落 p 元素中,该元素属于类 course__description(两个下划线)。

本练习是课程的一部分

Python Web 爬取

查看课程

练习说明

  • parse_pages 方法下方的唯一空白处填写一个 CSS 定位器字符串,用于定位属于类 course__description 的段落 p 元素中的文本。

注意:如果您点击了 Run Code,必须使用 "重置为示例代码" 才能再次成功使用 Run Code!!

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Import scrapy
import scrapy

# Import the CrawlerProcess: for running the spider
from scrapy.crawler import CrawlerProcess

# Create the Spider class
class DC_Description_Spider(scrapy.Spider):
  name = "dc_chapter_spider"
  # start_requests method
  def start_requests(self):
    yield scrapy.Request(url = url_short,
                         callback = self.parse_front)
  # First parsing method
  def parse_front(self, response):
    course_blocks = response.css('div.course-block')
    course_links = course_blocks.xpath('./a/@href')
    links_to_follow = course_links.extract()
    for url in links_to_follow:
      yield response.follow(url = url,
                            callback = self.parse_pages)
  # Second parsing method
  def parse_pages(self, response):
    # Create a SelectorList of the course titles text
    crs_title = response.xpath('//h1[contains(@class,"title")]/text()')
    # Extract the text and strip it clean
    crs_title_ext = crs_title.extract_first().strip()
    # Create a SelectorList of course descriptions text
    crs_descr = response.css( ____ )
    # Extract the text and strip it clean
    crs_descr_ext = crs_descr.extract_first().strip()
    # Fill in the dictionary
    dc_dict[crs_title_ext] = crs_descr_ext

# Initialize the dictionary **outside** of the Spider class
dc_dict = dict()

# Run the Spider
process = CrawlerProcess()
process.crawl(DC_Description_Spider)
process.start()

# Print a preview of courses
previewCourses(dc_dict)
编辑并运行代码