加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 使用BeautifulSoup基于内容值提取标记内容

发布时间:2020-12-20 11:22:59 所属栏目:Python 来源:网络整理
导读:我有一个以下格式的 Html文档. pnbsp;nbsp;nbsp;1. Content of the paragraph i in italic /i but not b strong /b a href="url"ignore/a./p 我想提取段落标记的内容,包括斜体和粗体标记的内容,但不包含锚标记的内容.此外,可能在开头忽略数字. 预期的产出是
我有一个以下格式的 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”的参数不可迭代

soup = BSoup(page)
for p in soup.findAll('p'):
    if '&nbsp;&nbsp;&nbsp;' in p.string:
        print p

谢谢你的建议.

解决方法

您的代码失败,因为如果标记只有一个子节点并且该子节点是NavigableString,则设置tag.string

您可以通过提取标签来实现您想要的效果:

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))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读