【问题标题】:xpath to get only the content not the self tagxpath 仅获取内容而不是 self 标记
【发布时间】:2017-11-08 17:50:09
【问题描述】:
<div id="content">
   foo <br/>
   bar <br/>
</div>

我正在尝试使用以下内容获取上面content div 的内部文本:

response.xpath('//div[@id ="content"]').extract()

这给了我以下信息:

[u'<div id="content"> foo<br/>bar <br/></div>

如何获得:

foo<br/>bar</br>

【问题讨论】:

  • 您使用什么语言调用 response.xpath 和 .extract()?
  • 更新了问题。

标签: python xpath scrapy


【解决方案1】:

试试这个:

''.join(map(methodcaller('strip'), response.xpath('//div[@id ="content"]/node()').extract()))
# output: u'foo<br>bar<br>'

请注意,这会将&lt;br /&gt; 更改为&lt;br&gt; lxml,但如果您不需要这些内部标签,您可以这样做:

response.xpath('normalize-space(//div[@id ="content"])').extract_first()
# output: u'foo bar'

【讨论】:

  • 这将失去区分元素和文本的能力(例如&amp;lt;b&amp;gt;)。
【解决方案2】:

lxml 在很多地方都非常不方便——获取元素的内部 HTML 就是其中之一。改编自an answer by lormus

from lxml import html

def inner_html(element):
    return (
        (element.text or '') +
        ''.join(html.tostring(child, encoding='unicode') for child in element)
    )

使用中:

>>> from scrapy.selector import Selector
>>> response = Selector(text="""
... <div id="content">
...    foo <br/>
...    bar <br/>
... </div>
... """)
>>> inner_html(response.css('#content')[0].root)
'\n   foo <br>\n   bar <br>\n'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-24
    • 1970-01-01
    • 2014-10-11
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    • 1970-01-01
    相关资源
    最近更新 更多