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

我使用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.

上一篇:html 网页源码解析:bs4中BeautifulSoup


下一篇:bs4-BeautifulSoup