我有一个如下格式的 Html 文档。
<p> 1. Content of the paragraph <i> in italic </i> but not <b> strong </b> <a href="url">ignore</a>.</p>
我想提取段落标签的内容,包括斜体和粗体标签的内容,但不包括 anchor 标签的内容。此外,可能会在开始时忽略数字。
预期的输出是: 斜体但不粗的段落内容。
最好的方法是什么?
此外,以下代码片段返回 TypeError: argument of type 'NoneType' is not iterable
soup = BSoup(page)
for p in soup.findAll('p'):
if ' ' in p.string:
print p
感谢您的建议。
最佳答案
您的代码失败,因为如果标签只有一个子标签且该子标签是 NavigableString
,则设置了 tag.string
你可以通过提取a
标签来实现你想要的:
from BeautifulSoup import BeautifulSoup
s = """<p> 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))
关于python - 使用 BeautifulSoup 根据内容值提取标签内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8909481/