【问题标题】:BeautifulSoup : create and insert self closing tag between a tagBeautifulSoup:在标签之间创建和插入自闭标签
【发布时间】:2020-10-05 04:29:36
【问题描述】:

我正在解析 html 文件并用新标签替换特定链接。

Python 代码:

from bs4 import BeautifulSoup
sample='''<a href="{Image src='https://google.com' link='https://google.com'}" >{Image src='https://google.com' link='google.com'}</a>'''
soup=BeautifulSoup(sample)
for a in soup.findAll('a'):
    x=BeautifulSoup('<ac:image><ri:attachment ri:filename="somefile"/> </ac:image>')
    a=a.replace_with(x)

print(soup)

实际输出:

<ac:image><ri:attachment ri:filename="somefile"></ri:attachment> </ac:image>

所需的输出:

<ac:image><ri:attachment ri:filename="somefile" /></ac:image>

自动关闭标签会自动转换。目的地严格需要自闭标签。

任何帮助将不胜感激!

【问题讨论】:

  • 您忘记包含代码,请将其添加到帖子中。
  • 您可以编辑您的问题并发布输入/您的代码吗?
  • @Sushanth ,添加了所需输出和实际输出的代码。

标签: python html python-3.x beautifulsoup tags


【解决方案1】:

要获得正确的自闭合标签,请在创建将替换旧标签的新汤时使用解析器 xml

另外,为了保留acri 命名空间,xml 解析器需要定义xmlns:acxmlns:ri 参数。我们在处理后删除的虚拟标签中定义这些参数。

例如:

from bs4 import BeautifulSoup
import xml
txt = '''
<div class="my-class">
    <a src="some address">
        <img src="attlasian_logo.gif" />
    </a>
</div>
<div class="my-class">
    <a src="some address2">
        <img src="other_logo.gif" />
    </a>
</div>
'''

template = '''
<div class="_remove_me" xmlns:ac="http://namespace1/" xmlns:ri="http://namespace2/">
<ac:image>
  <ri:attachment ri:filename="{img_src}" />
</ac:image>
</div>
'''

soup = BeautifulSoup(txt, 'html.parser')

for a in soup.select('a'):
    a=a.replace_with(BeautifulSoup(template.format(img_src=a.img['src']), 'xml'))  # <-- select `xml` parser, the template needs to have xmlns:* parameters to preserve namespaces

for div in soup.select('div._remove_me'):
    dump=div.unwrap()

print(soup.prettify())

打印:

<div class="my-class">
 <ac:image>
  <ri:attachment ri:filename="attlasian_logo.gif"/>
 </ac:image>
</div>
<div class="my-class">
 <ac:image>
  <ri:attachment ri:filename="other_logo.gif"/>
 </ac:image>
</div>

【讨论】:

  • replace_withTraceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; File "C:\Users\**\AppData\Local\Programs\Python\Python37-32\lib\site-packages\bs4\__init__.py", line 245, in __init__ % ",".join(features)) bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: xml. Do you need to install a parser library? 'xml' 解析器抛出错误
  • @Yash 是的,你需要在 Python 中安装 lxml 模块。
  • import xml 完成了这项工作。
猜你喜欢
  • 2023-03-24
  • 2017-12-25
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多