在Scrapy中禁用SSL证书验证

时间:2015-10-05 14:10:57

标签: python ssl scrapy

我目前正在努力解决与Scrapy有关的问题。每当我使用Scrapy刮取证书的CN值与服务器域名匹配的HTTPS站点时,Scrapy效果很好!另一方面,每当我尝试抓取证书的CN值与服务器的域名不匹配的网站时,我会得到以下内容:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/twisted/protocols/tls.py", line 415, in dataReceived
    self._write(bytes)
  File "/usr/local/lib/python2.7/dist-packages/twisted/protocols/tls.py", line 554, in _write
    sent = self._tlsConnection.send(toSend)
  File "/usr/local/lib/python2.7/dist-packages/OpenSSL/SSL.py", line 1270, in send
    result = _lib.SSL_write(self._ssl, buf, len(buf))
  File "/usr/local/lib/python2.7/dist-packages/OpenSSL/SSL.py", line 926, in wrapper
    callback(Connection._reverse_mapping[ssl], where, return_code)
--- <exception caught here> ---
  File "/usr/local/lib/python2.7/dist-packages/twisted/internet/_sslverify.py", line 1055, in infoCallback
    return wrapped(connection, where, ret)
  File "/usr/local/lib/python2.7/dist-packages/twisted/internet/_sslverify.py", line 1154, in _identityVerifyingInfoCallback
    verifyHostname(connection, self._hostnameASCII)
  File "/usr/local/lib/python2.7/dist-packages/service_identity/pyopenssl.py", line 30, in verify_hostname
    obligatory_ids=[DNS_ID(hostname)],
  File "/usr/local/lib/python2.7/dist-packages/service_identity/_common.py", line 235, in __init__
    raise ValueError("Invalid DNS-ID.")
exceptions.ValueError: Invalid DNS-ID.

我尽可能多地查看了文档,据我所知,Scrapy没有办法禁用SSL证书验证。甚至Scrapy Request对象的文档(我假设这个功能所在的位置)也没有引用:

http://doc.scrapy.org/en/1.0/topics/request-response.html#scrapy.http.Request https://github.com/scrapy/scrapy/blob/master/scrapy/http/request/init.py

也没有解决问题的Scrapy设置:

http://doc.scrapy.org/en/1.0/topics/settings.html

如果没有按源使用Scrapy并根据需要修改源代码,是否有人对如何禁用SSL证书验证有任何想法?

谢谢!

1 个答案:

答案 0 :(得分:5)

在您为the settings关联的文档中,您似乎可以修改DOWNLOAD_HANDLERS设置。

来自文档:

"""
    A dict containing the request download handlers enabled by default in
    Scrapy. You should never modify this setting in your project, modify
    DOWNLOAD_HANDLERS instead.
"""

DOWNLOAD_HANDLERS_BASE = {
    'file': 'scrapy.core.downloader.handlers.file.FileDownloadHandler',
    'http': 'scrapy.core.downloader.handlers.http.HttpDownloadHandler',
    'https': 'scrapy.core.downloader.handlers.http.HttpDownloadHandler',
    's3': 'scrapy.core.downloader.handlers.s3.S3DownloadHandler',
}

然后在你的设置中,这样的事情:

""" 
    Configure your download handlers with something custom to override
    the default https handler
"""
DOWNLOAD_HANDLERS = {
    'https': 'my.custom.downloader.handler.https.HttpsDownloaderIgnoreCNError',
}

因此,通过为https协议定义自定义处理程序,您应该能够处理您所获得的错误,并允许scrapy继续其业务。