"Python的xml.findall()返回空列表"

2024-09-29 23:32:44 发布

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

我尽力解析xml字符串,但在搜索子元素时它返回一个空列表。我可以提供一个工作Python小提琴:

https://onlinegdb.com/SytNQIOcS

但归根结底是:

root = ET.fromstring(xml_string)
print(root.findall('Race'))

有什么建议吗?看起来是个初学者的错误。。你知道吗


Tags: 字符串httpscom元素列表stringrootxml
1条回答
网友
1楼 · 发布于 2024-09-29 23:32:44
root = ET.fromstring(xml_string)
namespace = {'ns': 'http://ergast.com/mrd/1.4' }

for race in root.find('ns:RaceTable', namespace):
    round_num = race.get("round")
    circuit = race.find('ns:RaceName', namespace).text
    date = race.find("ns:Date", namespace).text
    time = race.find("ns:Time", namespace).text
    print(round_num, circuit, date, time)

错误:

  1. Element.findall() finds only elements with a tag which are direct children of the current element.
  2. If the XML input has namespaces, tags and attributes with prefixes in the form prefix:sometag get expanded to {uri}sometag where the prefix is replaced by the full URI. Also, if there is a default namespace, that full URI gets prepended to all of the non-prefixed tags. Checkout this documentation https://docs.python.org/2/library/xml.etree.elementtree.html#parsing-xml-with-namespaces

你可以用这样的东西

相关问题 更多 >

    热门问题