NameError:使用Scrapy时未定义名称'hxs'

Mat*_*ien 3 scrapy web-scraping

我已经推出了Scrapy shell并且成功地为维基百科做了准备.

scrapy shell http://en.wikipedia.org/wiki/Main_Page

我相信这一步是正确的,从Scrapy的反应的冗长性质来判断.

接下来,我想看看写作时会发生什么

hxs.select('/html').extract()

此时,我收到错误:

NameError: name 'hxs' is not defined

问题是什么?我知道Scrapy安装得很好,已经接受了目的地的URL,但是为什么hxs命令会出现问题?

ale*_*cxe 7

我怀疑你正在使用的是没有hxsshell 的Scrapy版本了.

sel改用(在0.24之后弃用,见下文):

$ scrapy shell http://en.wikipedia.org/wiki/Main_Page
>>> sel.xpath('//title/text()').extract()[0]
u'Wikipedia, the free encyclopedia'
Run Code Online (Sandbox Code Playgroud)

或者,从Scrapy 1.0开始,你应该使用它的Selector对象response,以及它.xpath.css方便的方法:

$ scrapy shell http://en.wikipedia.org/wiki/Main_Page
>>> response.xpath('//title/text()').extract()[0]
u'Wikipedia, the free encyclopedia'
Run Code Online (Sandbox Code Playgroud)

仅供参考,请参阅Scrapy文档中的使用选择器:

...在shell加载之后,您将获得响应作为responseshell变量,并在response.selector属性中附加选择器.
...
使用XPath和CSS查询响应非常常见,响应包括两个便捷快捷方式:response.xpath()response.css():

>>> response.xpath('//title/text()')
[<Selector (text) xpath=//title/text()>]
>>> response.css('title::text')
[<Selector (text) xpath=//title/text()>]