Skip to main content
 首页 » 编程设计

Python BeautifulSoup 不会从 XML 返回标签

2024年11月01日10wayfarer

在我的工作目录中给出以下名为 test.xml 的 XML:

<workbook> 
    <style> 
          <style-rule element='worksheet'> 
            <format attr='font-family' value='Tahoma' /> 
            <format attr='font-size' value='15' /> 
            <format attr='font-weight' value='bold' /> 
            <format attr='color' value='#ffbe7d' /> 
          </style-rule> 
    </style> 
</workbook> 

我正在尝试返回 style-rule 中的元素,并最终返回每个 format 元素。我已经尝试了下面的 python 代码并返回了 None:

from bs4 import BeautifulSoup 
import os 
 
with open(os.getcwd()+'//test.xml') as xmlfile: 
    soup = BeautifulSoup(xmlfile, 'html.parser') 
    print(soup.style.find('style-rule')) 

由于元素名称中存在连字符,我知道使用 find 命令,并且在 xml 文件的其他带连字符的部分成功使用了此技术。但是,由于某种我不知道的原因,这个实例给我带来了问题。

请您参考如下方法:

问题不是因为连字符,如果您尝试打印样式标签的 innerText,出于某种原因您将获得字符串类型的样式规则。

我的猜测是样式标签通常带有在 bs4 中被视为字符串的内容,但在这里您将其用作 html 容器。

解决方法:

from bs4 import BeautifulSoup 
import os 
 
soup = BeautifulSoup(text) 
soup = BeautifulSoup(soup.find('style').text) 
 
for format in soup.select('style-rule > format'): 
  print(format) 

演示: Here