【问题标题】:geoPy error: AttributeError: 'NoneType' object has no attribute 'address'geoPy 错误:AttributeError:“NoneType”对象没有属性“地址”
【发布时间】:2014-08-12 09:57:37
【问题描述】:

我有一个带有地址列表的 xml,我正在尝试遍历它们并使用 geopy 提取信息(即:纬度、经度、距离等),但我不断收到此错误:AttributeError:'NoneType ' 对象没有属性 'address'。 这是代码,如果有人有任何想法:

import xml.etree.ElementTree as et
import urllib, json
from geopy.geocoders import Nominatim

geolocator = Nominatim()
root = et.parse('data.xml').getroot()

for child in root:
    adress = child.find('adress').text + ' beer sheva'
    location = geolocator.geocode(adress)
    print location.address # i'm trying to acces some information here.

对于 xml 文件的示例:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ShelterInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <Shelter>
        <adress>אחד העם 21</adress>
        <code>1 - א</code>
        <neighborhood>א</neighborhood>
    </Shelter>
    <Shelter>
        <adress>13 שלח</adress>
        <code>10 - א</code>
        <neighborhood>א</neighborhood>
    </Shelter>
    <Shelter>
        <adress>ביאליק</adress>
        <code>11 - א</code>
        <neighborhood>א</neighborhood>
    </Shelter>

您可以知道地址是希伯来语,但它不应该造成问题。对于第一个地址,一切正常,但后来我得到了错误。我猜这与我遍历 xml 文件的方式有关,有什么想法吗?

非常感谢!

【问题讨论】:

  • 显然geolocator.geocode(...) 正在返回None。你看过the docs,还是the source?检查 adress 到底是什么?
  • adress 是一个带有地址的字符串(只是拼错了;))所以它应该作为对该地址的查询运行。
  • 我的意思是,你试过print adress吗?它看起来像你期望的那样吗?您是否尝试在与文字字符串相同的值上运行 geolocator.geocode?那你收到回复了吗?
  • 哦,是的,我忘记了,是的,我有,如果我真的把每个地址都写成一个字符串,它工作正常,但如果我在那个 for 循环中运行它们,就会出现严重错误.这就是为什么我的直觉是循环内部出现问题 - 也许是实例化?但应该可以正常工作,它只是一个字符串。与“打印地址”相同
  • 好的,所以我再次通过数据集运行它,我认为地址本身有问题。

标签: python xml geolocation geocoding geopy


【解决方案1】:

首先,我将使用这些来处理您的 TimedOut 错误,而不是 Nominatim。

from geopy import geocoders
from geopy.exc import GeocoderTimedOut

另外注册API key with Google Developers Console。 它将您限制为每天 2,500 次查询,但这对于您的 262 地址应该不是问题。完成后,您可以使用以下内容非常简单地进行地理编码。

g = geocoders.GoogleV3(api_key='yourApiKeyHere')
location = g.geocode(address, timeout=10)
print(location.address)

或者您也可以单独查看经度和纬度。

print(location.longitude, location.latitude)

这个版本比 Nomatims 更好地处理不正确的数据,但您仍然应该将所有内容放入几个 try/except 块中以确保。所以你的最终代码应该是这样的。

g = geocoders.GoogleV3(api_key='yourApiKeyHere')
try:
    location = g.geocode(address, timeout=10)
    print(location.address)
except AttributeError:
    print("Problem with data or cannot Geocode."
except GeocoderTimedOut:
    # possibly use recursion to have it run until it no longer runs into a timeout error

希望对您有所帮助!干杯!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-20
    • 2018-06-21
    • 2017-03-10
    • 2019-07-18
    • 2018-01-27
    • 1970-01-01
    相关资源
    最近更新 更多