scrapy:将 html 字符串转换为 HtmlResponse 对象 [英] scrapy: convert html string to HtmlResponse object
问题描述
我有一个原始 html 字符串,我想将其转换为 scrapy HTML 响应对象,以便我可以使用选择器 css
和 xpath
,类似于 scrapy 的 响应
.我该怎么做?
I have a raw html string that I want to convert to scrapy HTML response object so that I can use the selectors css
and xpath
, similar to scrapy's response
. How can I do it?
推荐答案
首先,如果是为了调试或者测试目的,可以使用 Scrapy shell
:
First of all, if it is for debugging or testing purposes, you can use the 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'
$scrapy shell index.html>>>response.xpath('//div[@id="test"]/text()').extract()[0].strip()u'测试文本'
There are different objects available in the shell during the session, like response
and request
.
shell 中有不同的可用对象 在会话期间,例如 response
和 request
.
Or, you can instantiate an HtmlResponse
class and provide the HTML string in body
:
或者,您可以实例化一个 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'
这篇关于scrapy:将 html 字符串转换为 HtmlResponse 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!