首页 > 解决方案 > 如何停止 Scrapy Selector 用 html 包装 xml?

问题描述

我这样做:

xmlstr="<root><first>info</first></root>"

res = Selector(text=xmlstr).xpath('.').getall()
print(res)

输出是:

['<html><body><root><first>info</first></root></body></html>']

如何停止选择器用 html 和 body 包装 xml?谢谢

标签: pythonxpathscrapy

解决方案


scrapy.Selector假定为 html,但需要一个type参数来改变它。

type定义选择器类型,它可以是"html""xml"None(默认)。

如果typeNone,选择器会根据类型自动选择最佳类型response(见下文),或者默认为"html"以防它与文本一起使用。

所以,要制作一个 xml 选择器,只需使用Selector(text=xmlstr, type='xml')


推荐阅读