【问题标题】:How to retrieve information from xml tspan tag如何从 xml tspan 标签中检索信息
【发布时间】:2019-12-27 03:23:33
【问题描述】:

我目前正在使用 BeautifulSoup 进行 xml 解析,但不知道如何从 tspan 标签中获取信息。我正在解析的 xml 如下所示:

<text
           transform="matrix(0,-1,-1,0,7931,3626)"
           style="font-variant:normal;font-weight:normal;font-size:92.3259964px;font-family:Arial;-inkscape-font-specification:ArialMT;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
           id="text60264"><tspan
             x="0 61.581444 123.16289 184.74432 251.4037 323.23334 384.81476 410.48138 436.14801 497.72946 559.31091 625.97028 692.62964 754.21112 805.54437 831.211 918.3667 979.94818 1005.6148 1077.4445 1144.1038 1200.515 1226.1816 1256.9261 1318.5076 1390.3373 1421.0818 1446.7484 1472.415 1526.3334 1587.9149 1649.4963 1716.1556 1782.8151 1844.3965 1895.7297 1921.3964 2008.5521 2070.1335 2095.8003 2167.6299 2234.2893 2290.7004"
             y="0"
             sodipodi:role="line"
             id="tspan60262">APPROX. BARREL WEIGHT (KG): &lt;BARREL WEIGHT&gt;</tspan></text>

我可以从文本标签中获取文本,但我正在尝试获取x="0 61.581...",以便将其更改为x="0"。到目前为止,我的代码只获取 tspan xml 标签

from bs4 import BeautifulSoup


infile = open('1c E37 Face Electric Operation No No.svg', 'r')
contents = infile.read()
soup = BeautifulSoup(contents, 'lxml')
items = soup.find_all('tspan')
for item in items:
    print(item) 

【问题讨论】:

  • 意识到我只需要做item.get('x')

标签: python xml beautifulsoup


【解决方案1】:

您也可以使用 css 选择器 - 通过将 x 属性添加到选择器中,您将只获取存在该属性的元素

from bs4 import BeautifulSoup as bs

s = '''
<text
transform="matrix(0,-1,-1,0,7931,3626)"
style="font-variant:normal;font-weight:normal;font-size:92.3259964px;font-family:Arial;-inkscape-font-specification:ArialMT;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
id="text60264"><tspan
 x="0 61.581444 123.16289 184.74432 251.4037 323.23334 384.81476 410.48138 436.14801 497.72946 559.31091 625.97028 692.62964 754.21112 805.54437 831.211 918.3667 979.94818 1005.6148 1077.4445 1144.1038 1200.515 1226.1816 1256.9261 1318.5076 1390.3373 1421.0818 1446.7484 1472.415 1526.3334 1587.9149 1649.4963 1716.1556 1782.8151 1844.3965 1895.7297 1921.3964 2008.5521 2070.1335 2095.8003 2167.6299 2234.2893 2290.7004"
 y="0"
 sodipodi:role="line"
 id="tspan60262">APPROX. BARREL WEIGHT (KG): &lt;BARREL WEIGHT&gt;</tspan></text>
'''

soup = bs(s, 'lxml')
print([i['x'] for i in soup.select('tspan[x]')])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 2011-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-02
    相关资源
    最近更新 更多