我尝试运行代码时遇到此错误:
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()
答案 0 :(得分:1)
如果没有最新版本的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
答案 1 :(得分:1)
在你阻止机械化代码之前把它放到魅力
import ssl
try:
make_non_ssl_context = ssl._create_verified_context
except AttributeError:
pass
else:
ssl._create_default_https_context = make_non_ssl
答案 2 :(得分:0)
Python核心和库有几个与SSL相关的关键修复。
除非您已使用最新的2.7.x python版本和最新的机械版本,否则这是使用过时库的简单示例。
是的,关于SSL的有趣部分是昨天工作的相同代码明天可能无法正常工作。