使用代理实例化geopy.geocoders.GoogleV3会导致异常

时间:2013-10-30 11:36:28

标签: python geopy

我试图像这样调用GoogleV3地理定位器:

geolocator = GoogleV3(proxies={"http": "http://user:password@ip:port"})
address, (latitude, longitude) = geolocator.geocode('address to geocode')

它提出了:

AttributeError: OpenerDirector instance has no __call__ method

我做错了什么?如何解决?

1 个答案:

答案 0 :(得分:0)

目前GoogleV3的实施无法将用户和密码变量直接传递给urllib2.opener(GoogleV3在幕后使用urllib2)。

以下是应该如何调用urllib2.opener的示例:

proxy_handler = urllib2.ProxyHandler({'http': 'http://www.example.com:3128/'})
proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
proxy_auth_handler.add_password('realm', 'host', 'username', 'password')

opener = urllib2.build_opener(proxy_handler, proxy_auth_handler)
# This time, rather than install the OpenerDirector, we use it directly:
opener.open('http://www.example.com/login.html')

可悲的是,但目前的GoogleV3实施并未使用urllib2.ProxyBasicAuthHandler。

因此,您需要通过修改源代码来扩展它:https://github.com/geopy/geopy/blob/master/geopy/geocoders/base.py 在顶部添加:

来自urlparse import urlparse

然后找到'if self.proxies是None:'代码并将其替换为:

    if self.proxies is None:
        self.urlopen = urllib_urlopen
    else:
        params = urlparse(proxies[1])
        host = params.get('hostname')
        username = params.get('username')
        password = params.get('password')
        if host and username and password:
            proxy_auth_handler = urllib2.ProxyBasicAuthHandler()
            proxy_auth_handler.add_password(None, host, username, password)
            self.urlopen = build_opener(
               ProxyHandler(self.proxies, proxy_auth_handler),
            )