Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python urllib.urlopen出现[SSL:CERTIFICATE\u VERIFY\u FAILED]错误_Python_Python 2.7_Ssl - Fatal编程技术网

Python urllib.urlopen出现[SSL:CERTIFICATE\u VERIFY\u FAILED]错误

Python urllib.urlopen出现[SSL:CERTIFICATE\u VERIFY\u FAILED]错误,python,python-2.7,ssl,Python,Python 2.7,Ssl,我对Python比较陌生。尝试用Python编写一个函数,该函数将使用Google distance Matrix API计算位置之间的距离。事实上,我在过去成功地使用了这段代码,但现在我遇到了以下错误,无法理解到底发生了什么 IOError:[Errno socket error][SSL:CERTIFICATE\u VERIFY\u FAILED]证书验证失败(\u SSL.c:590) 我知道问题不在于URL,因为我可以使用API键在浏览器中键入URL,它会给出我要查找的结果(即Googl

我对Python比较陌生。尝试用Python编写一个函数,该函数将使用Google distance Matrix API计算位置之间的距离。事实上,我在过去成功地使用了这段代码,但现在我遇到了以下错误,无法理解到底发生了什么

IOError:[Errno socket error][SSL:CERTIFICATE\u VERIFY\u FAILED]证书验证失败(\u SSL.c:590)

我知道问题不在于URL,因为我可以使用API键在浏览器中键入URL,它会给出我要查找的结果(即Google Maps distance Matrix API中的距离信息)。这似乎是urllib.urlopen函数调用的问题。我想我是说得不对,但我不知道怎么说。有什么想法吗

我使用的是Python版本2.7.10

import urllib
import re

def getMiles(origin,destination):
    #APIkey = "someAPIkey"  #Update to prompt user for API key
    query = "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=" + origin + "&destinations=" + destination + "&key=" + APIkey
    test = 0

fhand = urllib.urlopen(query)  #CODE ERRORS OUT HERE
#Error handling to ensure query works
try:
    for line in fhand:
        line = str(line.strip())
        #print line
        if test == 1:
            line = line.replace('"text" : "',"")
            line = line.replace('",',"")
            result = [origin,'"'+destination+'"'] + line.split()
            break
        if line.startswith('"distance"'):
            test = 1
    return result
except:
    result = [origin,'"'+destination+'"',"ERROR","Query could not be opened"]
    return result

这是一个对我有效的解决方案,在你的程序中添加以下代码,它会修复你的错误,伙计

import ssl
ssl._create_default_https_context = ssl._create_unverified_context


请看这里:答案是,不在生产环境中运行是邪恶的。这是什么意思?我只是做了一个分析,没有把这些放进任何软件。。。我想我会很好地使用这段代码?它似乎对我很有用(即当我删除try/except行时):{“destination_addresses”:[],“error_message”:“提供的API密钥无效。”,“origin_addresses”:[],“rows”:[],“status”:“REQUEST_DENIED”}来自googleI添加了以ctx=ssl开头的代码块。create_default_context(),并且还更新了我的代码,改为使用urllib2,但是现在我得到了一个HTTPError:HTTP Error 400:Bad请求,我不确定这意味着什么,因为如果我在抛出错误之前打印出URL,我可以将其复制并粘贴到浏览器中,然后解决问题。我遗漏了什么?导致URL在浏览器中工作但不在脚本中的一个常见原因是浏览器正在使用代理连接到目标,而脚本没有使用,或者使用公司防火墙或桌面AV/防火墙进行合法SSL拦截,并且浏览器已在信任存储中包含所需的代理CA而自从浏览器和Python使用不同的信任存储以来,脚本就没有使用过。但是在你的问题中没有足够的信息来知道哪种情况是这样的。