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

如何保留“和使用bs4 python解析xml时

发布时间:2020-12-20 13:48:49 所属栏目:Python 来源:网络整理
导读:我使用bs4解析xml文件,然后再将其写回新的xml文件. 输入文件: tag1 tag2 attr1="a1"quot; example text quot;/tag2 tag3 tag4 attr2="a2"quot; example text quot;/tag4 tag5 tag6 attr3="a3"apos; example text apos;/tag6 /tag5 /tag3/tag1 脚本: soup =
我使用bs4解析xml文件,然后再将其写回新的xml文件.

输入文件:

<tag1>
  <tag2 attr1="a1">&quot; example text &quot;</tag2>
  <tag3>
    <tag4 attr2="a2">&quot; example text &quot;</tag4>
    <tag5>
      <tag6 attr3="a3">&apos; example text &apos;</tag6>
    </tag5>
  </tag3>
</tag1>

脚本:

soup = BeautifulSoup(open("input.xml"),"xml")
f = open("output.xml","w") 
f.write(soup.encode(formatter='minimal'))
f.close()

输出:

<tag1>
  <tag2 attr1="a1"> " example text "  </tag2>
  <tag3>
    <tag4 attr2="a2"> " example text " </tag4>
    <tag5>
      <tag6 attr3="a3"> ' example text ' </tag6>
    </tag5>
  </tag3>
</tag1>

我想保留& quot;和& .我尝试使用编码格式化程序的所有选项 – Minimal,xml,html,none.但他们都没有解决这个问题.

然后我尝试手动替换“with& quot;”.

for tag in soup.find_all(text=re.compile(""")):
    res = tag.string
    res1 = res.replace(""","&quot;")
    tag.string.replaceWith(res1)

但这给出了以下输出

<tag1>
  <tag2 attr1="a1"> &amp;quot; example text &amp;quot;  </tag2>
  <tag3>
    <tag4 attr2="a2"> &amp;quot; example text &amp;quot; </tag4>
    <tag5>
      <tag6 attr3="a3"> &apos; example text &apos; </tag6>
    </tag5>
  </tag3>
</tag1>

它取代了&与& amp; amp; .我在这里很困惑.请帮我解决这个问题.

解决方法

自定义编码&输出格式

您可以使用custom formatter function将这些特定实体添加到实体替换中.

from bs4 import BeautifulSoup
from bs4.dammit import EntitySubstitution

def custom_formatter(string):
    """add &quot; and &apos; to entity substitution"""
    return EntitySubstitution.substitute_html(string).replace('"','&quot;').replace("'",'&apos;')

input_file = '''<tag1>
  <tag2 attr1="a1">&quot; example text &quot;</tag2>
  <tag3>
    <tag4 attr2="a2">&quot; example text &quot;</tag4>
    <tag5>
      <tag6 attr3="a3">&apos; example text &apos;</tag6>
    </tag5>
  </tag3>
</tag1>
'''

soup = BeautifulSoup(input_file,"xml")

print soup.encode(formatter=custom_formatter)
<?xml version="1.0" encoding="utf-8"?>
<tag1>
<tag2 attr1="a1">&quot; example text &quot;</tag2>
<tag3>
<tag4 attr2="a2">&quot; example text &quot;</tag4>
<tag5>
<tag6 attr3="a3">&apos; example text &apos;</tag6>
</tag5>
</tag3>
</tag1>

诀窍是在EntitySubstitution.substitute_html()之后执行此操作,因此您的& s不会替换为& amp; s.

(编辑:李大同)

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

    推荐文章
      热点阅读