【问题标题】:Xpath - get text separated by <p> tagsXpath - 获取由 <p> 标签分隔的文本
【发布时间】:2016-07-18 13:15:03
【问题描述】:

我不知道如何使用 xpath 从包含许多 &lt;span&gt; 标签和 &lt;p&gt; 标签的标签中获取格式化文本。

是这样的:

<span>This</span>
<span> is</span>
<span> main</span>
<span> text</span>
<p><span>First</span>
   <span>p-tag</span<
</p>
<p> second p tag ....

所以有两种类型的标签。 &lt;p&gt; 表示此标签内的文本在新行上。并且文本本身在&lt;span&gt;标签中被分成许多子串。

问题是&lt;p&gt; 中没有文本。

从上面的sn-p,我想得到(例如在列表中):

['This is main text','First p-tag','seco....]

这项工作,但它只得到&lt;p&gt;标签内的文本:

def get_popis_url(url):
    root = get_root(url)
    ps = root.xpath('//div[@class="description"]/p')
    for p in ps:
        text = p.xpath('string()').replace('&nbsp',' ').strip()
        print text

所以上面 html sn-p 的结果是:

First p-tag
second p tag

你有什么想法吗?

【问题讨论】:

  • 你为什么不试试这个:- //div[@class="description"]/*

标签: python xpath web-scraping


【解决方案1】:

我不确定您使用的是哪个 Python 库(xml.etree?)。但是关于 XPath,请尝试 './/div[@class="description"]//*'。这将选择div 处的所有子元素。

使用 xml.etree 它看起来像这样(假设 HTML 源代码以字符串形式给出):

def get_popis_url(html_source):
    import xml.etree.ElementTree as ET
    root = ET.fromstring(html_source)
    ps = root.findall('.//div[@class="description"]//*')
    for p in ps:
        text = p.text
        if text:
            print text.replace('&nbsp;',' ').strip()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-09
    • 1970-01-01
    • 2014-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    相关资源
    最近更新 更多