【问题标题】:Problem with XML-parsing using Beautiful Soup使用 Beautiful Soup 解析 XML 的问题
【发布时间】:2019-02-28 14:10:14
【问题描述】:

当尝试用 Beautiful Soup 替换 XML 中的某些元素时,我发现我必须使用 soup.find_all().string.replace_with() 来替换所需的元素。但是,我遇到了soup.find_all() 方法只返回None 类型的元素的问题。

所以我试图将我的问题分解为尽可能基本的 XML:

from bs4 import BeautifulSoup as BS

xml = """
<xml>
    <test tag="0"/>
    <test tag="1"/>
</xml>"""

soup = BS(xml, 'xml')
for elem in soup.find_all("test"):
    print('Element {} has type {}.'.format(elem, elem.type))

这给出了完全相同的东西:

Element <test tag="0"/> has type None.
Element <test tag="1"/> has type None.

如果有人能指出问题所在,我会很高兴。

提前致谢

【问题讨论】:

  • 你想在这里替换什么?
  • 您还想使用.name 代替吗? print('Element {} has type {}.'.format(elem, elem.name))
  • 对不起,应该说得更清楚。我想要做的是替换,例如,tag="0"with tag="2"。在这个例子中,我将通过在 for 循环中使用 elem.string.replace_with('test tag="2"') 来做到这一点。然而,这只是给AttributeError: 'NoneType' object has no attribute 'replace_with'
  • 好的,我在底部放了一个解决方案。这应该可以让您继续前进,但我会对其进行调整以反映您提供的示例输出
  • 问题是,"test tag="2" 不是该标签/元素中的字符串/文本。这是一个属性。所以你真正想要替换的不是字符串/文本,而是属性值

标签: xml python-3.x beautifulsoup


【解决方案1】:

好吧,我不确定您要寻找什么作为输出,但您可以通过以下方式替换标签属性:

from bs4 import BeautifulSoup as BS

xml = """
<xml>
    <test tag="0"/>
    <test tag="1"/>
</xml>"""

replace_list = ['0']
replacement = '2'

soup = BS(xml, 'xml')
for elem in soup.find_all("test"):
    if elem['tag'] in replace_list:
        elem['tag'] = replacement
    #print('Element {} has type {}.'.format(elem, elem.name))

xml = str(soup)

print (xml)

输出:

<?xml version="1.0" encoding="utf-8"?>
<xml>
<test tag="2"/>
<test tag="1"/>
</xml>

【讨论】:

  • 感谢您的解决方案。当我看到你的答案时,我自己找到了一个解决方案,使用elem.attrs['tag'] = '2'。我需要为不同的元素指定不同的替换,但这应该不是问题。
猜你喜欢
  • 2018-11-26
  • 2023-03-24
  • 2018-10-11
  • 1970-01-01
  • 1970-01-01
  • 2015-11-08
  • 2011-12-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多