我正在使用Python第二版阅读Web抓取,并希望使用Scrapy模块从网页中抓取信息。
我从文档中获得以下信息:https://docs.scrapy.org/en/latest/topics/request-response.html
回调(可调用)-该函数将以该请求的响应(一旦下载)作为其第一个参数来调用。有关更多信息,请参见将其他数据传递给下面的回调函数。如果请求没有指定回调,那么将使用蜘蛛的parse()方法。注意,如果在处理过程中引发异常,则将调用errback。
我的理解是:
问题是:
class ArticleSpider(scrapy.Spider):
name='article'
def start_requests(self):
urls = [
'http://en.wikipedia.org/wiki/Python_'
'%28programming_language%29',
'https://en.wikipedia.org/wiki/Functional_programming',
'https://en.wikipedia.org/wiki/Monty_Python']
return [scrapy.Request(url=url, callback=self.parse) for url in urls]
def parse(self, response):
url = response.url
title = response.css('h1::text').extract_first()
print('URL is: {}'.format(url))
print('Title is: {}'.format(title))
发布于 2020-07-04 19:34:14
似乎您缺少了一些与python类和OOP相关的概念。在python 文档或至少这个问题中读一读是个好主意。
以下是Scrapy的工作原理,您实例化了一个请求对象,并将其交给Scheduler。
yield scrapy.Request(url=url) #or use return like you did
Scrapy将处理请求,下载html,并将它得到的所有请求返回给回调函数。如果您没有在请求中设置回调函数(如上面的示例所示),它将调用名为parse
的默认函数。
解析是对象的一个方法(即.一个函数)。您在上面的代码中编写了它,即使没有,它仍然存在,因为您的类继承了它的父类的所有函数
class ArticleSpider(scrapy.Spider): # <<<<<<<< here
name='article'
所以你问题的答案是:
你没看到是因为它发生在家长课上。
2-您需要使用self.
,以便python知道您引用的是蜘蛛实例的方法。
3- self
参数是它self的实例,它被python使用。
响应是解析方法作为参数接收的独立对象,因此可以访问它的属性,如response.url
或response.headers
发布于 2020-07-04 19:31:19
有关self
的信息,您可以在这里找到- https://docs.python.org/3/tutorial/classes.html
关于这个问题:
can we extract URL from response parameter like this: url = response.url or should be url = self.url
您应该使用response.url
获取当前爬行/解析的页面的URL
https://stackoverflow.com/questions/62732038
复制相似问题