开跑时间
在上一节课中,我们一起创建了一个完整的网络爬虫,用来从 DataCamp 课程目录中访问每门课程的信息。不过,课程在讲完解析方法后就戛然而止,显得意犹未尽,因为我们还没有真正运行代码。
本练习就是为了解决这个问题!
接下来这道题和下一道题里,您会看到一段较长的代码,因为它就是我们整节课中构建的完整 spider。别被长度吓到!这两个练习给您的任务都非常简单,目的就是鼓励您看看这段 spider 的代码并运行它。这样,即使代码较长,您也能把握它的整体思路!
本练习是课程的一部分
Python Web 爬取
练习说明
- 在
parse_pages方法的末尾补全唯一的空白,将章节标题赋给以相应课程标题为键的字典。
注意:如果您点击了"运行代码",想要再次成功使用"运行代码",必须先点击"重置为示例代码"!!
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Import scrapy
import scrapy
# Import the CrawlerProcess: for running the spider
from scrapy.crawler import CrawlerProcess
# Create the Spider class
class DC_Chapter_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):
crs_title = response.xpath('//h1[contains(@class,"title")]/text()')
crs_title_ext = crs_title.extract_first().strip()
ch_titles = response.css('h4.chapter__title::text')
ch_titles_ext = [t.strip() for t in ch_titles.extract()]
dc_dict[ crs_title_ext ] = ____
# Initialize the dictionary **outside** of the Spider class
dc_dict = dict()
# Run the Spider
process = CrawlerProcess()
process.crawl(DC_Chapter_Spider)
process.start()
# Print a preview of courses
previewCourses(dc_dict)