开始使用免费开始使用

自引用很"优雅"

您可能已经注意到,在爬虫类中,我们总是在 start_requestsparse 方法里传入参数 self(就看本练习中的示例代码!)。这样做可以在类内部的方法之间互相引用。也就是说,如果我们想在 start_requests 方法中引用 parse 方法,就需要写成 self.parse,而不是只写 parse;添加 self 的作用是告诉代码:"去和 start_requests 同一个类里找名为 parse 的方法来用。"

在本练习中,您将实际动手体验这种"自引用"。

本练习是课程的一部分

Python Web 爬取

查看课程

练习说明

  • YourSpider 类中填入所需的 scrapy 对象,以创建 scrapy 爬虫。
  • start_requests 方法中,将字符串参数 "Hello World!" 传给空白处,以调用 print_msg 方法。

交互式实操练习

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

# Import scrapy library
import scrapy

# Create the spider class
class YourSpider( ____ ):
  name = "your_spider"
  # start_requests method
  def start_requests( self ):
    self.print_msg( ____ )
  # parse method
  def parse( self, response ):
    pass
  # print_msg method
  def print_msg( self, msg ):
    print( "Calling start_requests in YourSpider prints out:", msg )
  
# Inspect Your Class
inspect_class( YourSpider )
编辑并运行代码