使用BeautifulSoup4设置XML属性值

2024-04-28 16:12:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python中的BeautifulSoup读取、修改和保存(覆盖)我的svg文件

{}的内容:

<g data-default-color="#FFFFFF" data-element-id="X123456">
  <rect class="selection-box" fill="none" height="91" stroke="none" width="140" x="-30" y="-10"/>
  <circle cx="40" cy="25" data-colored="true" fill="red" pointer-events="visible" r="25" stroke="black" stroke-width="3"/>
  <text fill="black" font-family="Verdana" font-size="16" text-anchor="middle" x="40" y="55">
    <tspan dy="16" x="40">Label Text</tspan>
  </text>
</g>

这些内容实际上是一个更大的svg的子集,在这里我根据用户提供的data-element-id值查找g元素。 我想将circle元素的fill属性更改为“blue”

到目前为止,我所拥有的:

from bs4 import BeautifulSoup as bs

with open("bs-test.svg", "r") as f:
    contents = f.read()
    soup = bs(contents, "xml")

# grab g tags with the required data-element-id
elem_ls = soup.find_all(attrs={"data-element-id" : "X123456"})
x = elem_ls[0]
x

输出

<g data-default-color="#FFFFFF" data-element-id="X123456">
<rect class="selection-box" fill="none" height="91" stroke="none" width="140" x="-30" y="-10"/>
<circle cx="40" cy="25" data-colored="true" fill="red" pointer-events="visible" r="25" stroke="black" stroke-width="3"/>
<text fill="black" font-family="Verdana" font-size="16" text-anchor="middle" x="40" y="55">
<tspan dy="16" x="40">Label Text</tspan>
</text>
</g>

我确信这只是一个语法问题,我无法找到答案;我如何获取circlefill属性,用“blue”替换它的值,然后写出来


Tags: textsvgnoneiddatastrokebselement
2条回答

您只需使用键设置bs4元素的属性值

代码:

from bs4 import BeautifulSoup as bs

with open("bs-test.svg", "r") as f:
    contents = f.read()
    soup = bs(contents, "xml")

# grab g tags with the required data-element-id
elem_ls = soup.find_all(attrs={"data-element-id" : "X123456"})
for e in elem_ls:
    circle = e.find('circle')
    circle['fill'] = 'blue'

    print(e)

结果:

<g data-default-color="#FFFFFF" data-element-id="X123456">
<rect class="selection-box" fill="none" height="91" stroke="none" width="140" x="-30" y="-10"/>
<circle cx="40" cy="25" data-colored="true" fill="blue" pointer-events="visible" r="25" stroke="black" stroke-width="3"/>
<text fill="black" font-family="Verdana" font-size="16" text-anchor="middle" x="40" y="55">
<tspan dy="16" x="40">Label Text</tspan>
</text>
</g>

BeautifulSoup中,覆盖将使用replace_with()方法

from bs4 import BeautifulSoup as bs

svg = """<g data-default-color="#FFFFFF" data-element-id="X123456">
  <rect class="selection-box" fill="none" height="91" stroke="none" width="140" x="-30" y="-10"/>
  <circle cx="40" cy="25" data-colored="true" fill="red" pointer-events="visible" r="25" stroke="black" stroke-width="3"/>
  <text fill="black" font-family="Verdana" font-size="16" text-anchor="middle" x="40" y="55">
    <tspan dy="16" x="40">Label Text</tspan>
  </text>
</g>
"""

soup = bs(svg, 'html.parser')
circle = soup.find('circle')
circle['fill'] = 'blue'
    soup.find('circle').replace_with(circle)
print(soup)

相关问题 更多 >