【发布时间】:2020-07-04 17:06:03
【问题描述】:
我正在阅读 Web Scraping with Python 2nd Ed,并想使用 Scrapy 模块从网页中抓取信息。
我从文档中获得了以下信息:https://docs.scrapy.org/en/latest/topics/request-response.html
callback (callable) – 将被调用的函数 这个请求的响应(一旦它被下载)作为它的第一个 范围。有关详细信息,请参阅将附加数据传递给 下面的回调函数。如果请求未指定回调,则 将使用蜘蛛的 parse() 方法。请注意,如果有例外 在处理期间引发,而是调用 errback。
我的理解是:
-
传入 url 并像我们在 requests 模块中一样获得响应
resp = requests.get(url)
-
传入resp进行数据解析
解析(resp)
问题是:
- 我没有看到 resp 在哪里传入
- 为什么需要在参数解析前加上self关键字
- 在解析函数中从来没有使用self关键字,为什么要把它作为第一个参数?
- 我们可以像这样从响应参数中提取 url:url = response.url 还是应该是 url = self.url
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))
【问题讨论】:
-
scrapy 使用异步并被构建用作生成器(始终使用
yield),约定是在其处理response的任何函数中传递self, response