【问题标题】:Retrieve information using ElementTree使用 ElementTree 检索信息
【发布时间】:2021-12-14 15:53:01
【问题描述】:

我尝试使用 ElementTree 检索信息。我成功检索了许多属性,但处理可能因缺乏信​​息而停止。它显示此错误消息:

xml.etree.ElementTree.ParseError: no element found: line 1, column 0

这是我使用的代码:

import xml.etree.ElementTree

MyosmID = str(id_cinema)
r = requests.get("https://www.openstreetmap.org/api/0.6/node/"+MyosmID)
root = xml.etree.ElementTree.fromstring(r.content)

for child in root.iter('tag'):
    if child.attrib['k'] == 'website':
        website = child.attrib['v']
    if child.attrib['k'] == 'wikidata':
        wikidata = child.attrib['v']

我该如何解决这个错误情况?

【问题讨论】:

  • 在调用fromstring之前添加以下行:print(r.status_code) print(r.content);或者,如果您想在无效响应中引发错误,则只需 r.raise_for_status()
  • 我怀疑您收到 404 not found 响应,就像我在使用 MyosmID = '12345' 进行测试时所做的一样
  • 当我使用可能阻止处理的属性的 MyosmID = '630982183' 进行测试时,我收到上述相同的错误消息(在我的问题中)
  • 该输入出现了不同的错误。 requests.exceptions.HTTPError: 410 Client Error: Gone for url: https://www.openstreetmap.org/api/0.6/node/630982183
  • 当我这样做时,我也会收到 410 错误:Requests.exceptions.HTTPError: 410 Client Error: Gone for url: openstreetmap.org/api/0.6/node/630982183

标签: python openstreetmap elementtree


【解决方案1】:

我将此添加到我的代码中,问题已解决:

    MyosmID = str(id_cinema)
try : 
    r = requests.get("https://www.openstreetmap.org/api/0.6/node/"+MyosmID)
    r.raise_for_status()
    root = xml.etree.ElementTree.fromstring(r.content)
    
    fromstring: print(r.status_code) 
    
    for child in root.iter('tag'):
        if child.attrib['k'] == 'website':
            website = child.attrib['v']
        if child.attrib['k'] == 'wikidata':
            wikidata = child.attrib['v']
except Exception:
    pass 

感谢您的帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-08
    • 1970-01-01
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多