python - 如何使用 HtmlXPathSelector (Scrapy) 以 HTML 形式返回结果

标签 python xpath scrapy

如何检索标记内包含的所有 HTML?

hxs = HtmlXPathSelector(response)
element = hxs.select('//span[@class="title"]/')

也许是这样的:

hxs.select('//span[@class="title"]/html()')

编辑: 如果我看 documentation ,我只看到返回新 XPathSelectorList 的方法,或者只看到标签内的原始文本。 我想要检索的不是新列表或文本,而是标签内的 HTML 源代码。 例如:

<html>
    <head>
        <title></title>
    </head>
    <body>
        <div id="leexample">
            justtext
            <p class="ihatelookingforfeatures">
                sometext
            </p>
            <p class="yahc">
                sometext
            </p>
        </div>
        <div id="lenot">
            blabla
        </div>
    an awfuly long example for this.
    </body>
</html>

我想做一个像 hxs.select('//div[@id="leexample"]/html()') 这样的方法,它将返回其中的 HTML,像这样:

justtext
<p class="ihatelookingforfeatures">
    sometext
</p>
<p class="yahc">
    sometext
</p>

我希望我消除了围绕我的问题的歧义。

如何从 Scrapy 中的 HtmlXPathSelector 获取 HTML? (也许是 scrapy 范围之外的解决方案?)

最佳答案

在您的 XpathSelectorList 上调用 .extract()。它将返回包含您想要的 HTML 内容的 unicode 字符串列表。

hxs.select('//div[@id="leexample"]/*').extract()

更新

# This is wrong
hxs.select('//div[@id="leexample"]/html()').extract()

/html() 不是有效的 scrapy 选择器。要提取所有子项,请使用 '//div[@id="leexample"]/*''//div[@id="leexample"]/node()'。请注意,node() 将返回 textNode,结果类似于:

[u'\n   ',
 u'<a href="image1.html">Name: My image 1 
' ]

关于python - 如何使用 HtmlXPathSelector (Scrapy) 以 HTML 形式返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11463538/

相关文章:

python - pycharm 2.5.1导入sys报错

python - 从嵌套 json 列表中展平 Pandas DataFrame

java - 当 Selenium 中的 xpath 时,子元素未正确填充

python - 使用保存在本地系统中的 html 抓取文件

python - 从脚本抓取抓取总是在抓取后阻止脚本执行

python - matplotlib 连接到主页/后退/前进按钮事件

python - 根据 DataFrame 中的条件检索列

xml - 非常简单的 XSL/XPath 健全性检查

python selenium xpath 解决方案

python - 在 scrapy 中抓取 json 响应