使用机械化获取证书验证失败错误

Getting certificate verify failed error with mechanize

我在尝试运行代码时遇到此错误:

  File "C:\Python27\lib\site-packages\mechanize\_urllib2_fork.py", line 1118, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:581)>

我在 Windows 8.1 上运行它,我可以打开带有请求的 https 没有问题,但如果我使用 mechanize 则不会出现错误。 我的代码:

import mechanize


br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [('User-agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17')]

sign_in = br.open('https://www.amazon.com/ap/signin?_encoding=UTF8&openid.assoc_handle=usflex&openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.identity=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.mode=checkid_setup&openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0&openid.ns.pape=http%3A%2F%2Fspecs.openid.net%2Fextensions%2Fpape%2F1.0&openid.pape.max_auth_age=0&openid.return_to=https%3A%2F%2Fwww.amazon.com%2Fgp%2Fcss%2Fhomepage.html%3Fie%3DUTF8%26ref_%3Dnav_yam_ya')

br.select_form(name="signIn")
br["email"] = 'username'
br['password'] = 'password'
logged_in = br.submit()

对 Python 核心和库进行了多项与 SSL 相关的重要修复。

除非您已经在使用最新的 2.7.x python 版本和最新的 mechanize 版本,否则这是使用 过时库 的简单示例.

是的,关于 SSL 的有趣之处在于,昨天有效的相同代码明天可能就无效了。

我发现以下解决方法适用于我,以防没有最新版本的 python 或 mechanize。在调用 br.open() 之前添加以下代码:

import socket
import httplib
import ssl
def connect(self):
    sock = socket.create_connection((self.host, self.port),
                                self.timeout, self.source_address)
    if self._tunnel_host:
    self.sock = sock
    self._tunnel()

    self.sock = ssl.wrap_socket(sock, self.key_file, self.cert_file, ssl_version=ssl.PROTOCOL_TLSv1)

httplib.HTTPSConnection.connect = connect

把这个放在你的机械化代码块之前它会像魅力一样工作

import ssl

try:
    make_non_ssl_context = ssl._create_verified_context
except AttributeError:
    pass
else:
    ssl._create_default_https_context = make_non_ssl