基于内容值的标签内容提取

2024-04-25 01:08:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下格式的Html文档。在

<p>&nbsp;&nbsp;&nbsp;1. Content of the paragraph <i> in italic </i> but not <b> strong </b> <a href="url">ignore</a>.</p>

我想提取段落标签的内容,包括斜体和粗体标签的内容,而不是锚定标签的内容。另外,可能会忽略开头的数字。在

预期产出为: 段落内容为斜体,但不强。在

最好的办法是什么?在

另外,下面的代码片段返回TypeError:'NoneType'类型的参数不可编辑

^{pr2}$

谢谢你的建议。在


Tags: ofthein文档内容html格式标签
3条回答

我认为您只需遍历p中的标记并收集所需的字符串。在

使用lxml,可以使用XPath:

import lxml.html as LH
import re

content = '''\
<p>&nbsp;&nbsp;&nbsp;1. Content of the paragraph <i> in italic </i> but not <b> strong </b> <a href="url">ignore</a>.</p>'''

doc = LH.fromstring(content)
ptext = ''.join(doc.xpath('//p/descendant-or-self::*[not(self::a)]/text()'))
pat = r'^.*\d+.\s*'
print(re.sub(pat,'',ptext))

产量:

^{2}$

您的代码失败,因为如果标记只有一个子级并且该子级是NavigableString,则设置了{}

您可以通过提取a标记来实现您想要的:

from BeautifulSoup import BeautifulSoup

s = """<p>&nbsp;&nbsp;&nbsp;1. Content of the paragraph <i> in italic </i> but not <b> strong </b> <a href="url">ignore</a>.</p>"""
soup = BeautifulSoup(s, convertEntities=BeautifulSoup.HTML_ENTITIES)

for p in soup.findAll('p'):
    for a in p.findAll('a'):
        a.extract()
    print ''.join(p.findAll(text=True))

关于string的问题是因为string正如documentation中所解释的,它只适用于:

if a tag has onnly one child node, and that child node is a string

因此,在您的例子中,p.string是{},并且您不能迭代它。要访问标记内容,必须使用p.contents(这是一个包含标记的列表)或p.text(这是一个删除了所有标记的字符串)。在

在你的情况下,你可能在寻找这样的东西:

>>> ''.join([str(e) for e in soup.p.contents
                    if not isinstance(e, BeautifulSoup.Tag)
                       or e.name != 'a'])
>>> '&nbsp;&nbsp;&nbsp;1. Content of the paragraph <i> in italic </i> but not <b> strong </b> .'

如果还需要删除前缀“'”,我将使用正则表达式从最终字符串中删除该部分。在

相关问题 更多 >