yay*_*ayu 21 python scrapy web-scraping
我有我要转换为HTML scrapy响应对象,这样我就可以使用选择一个原始的HTML串css
并xpath
,类似scrapy的response
.我该怎么做?
ale*_*cxe 32
首先,如果是出于调试或测试目的,您可以使用Scrapy shell
:
$ cat index.html
<div id="test">
Test text
</div>
$ scrapy shell index.html
>>> response.xpath('//div[@id="test"]/text()').extract()[0].strip()
u'Test text'
Run Code Online (Sandbox Code Playgroud)
在会话期间,shell中有不同的对象,例如response
和request
.
或者,您可以实例化一个HtmlResponse
类并在body
以下位置提供HTML字符串:
>>> from scrapy.http import HtmlResponse
>>> response = HtmlResponse(url="my HTML string", body='<div id="test">Test text</div>', encoding='utf-8')
>>> response.xpath('//div[@id="test"]/text()').extract()[0].strip()
u'Test text'
Run Code Online (Sandbox Code Playgroud)
编辑:
你可能需要 Scrapy shell
小智 14
alecxe的答案是正确的,但这是在scrapy 中实例化 a Selector
from的正确方法:text
>>> from scrapy.selector import Selector
>>> body = '<html><body><span>good</span></body></html>'
>>> Selector(text=body).xpath('//span/text()').get()
'good'
Run Code Online (Sandbox Code Playgroud)