requests.exceptions.ConnectionError: HTTPSConnectionPool(host='baike.baidu.com', port=443):  Max retries exceeded with url: https://baike.baidu.com/item/%E5%88%98%E5%BE%B7%E5%8D%8E/114923  (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x7fb51433af98>:  Failed to establish a new connection: [Errno -2] Name or service not known',)

 

http连接太多没有关闭导致的

经过一番查询,发现该错误是因为如下:

http的连接数超过最大限制,默认的情况下连接是Keep-alive的,所以这就导致了服务器保持了太多连接而不能再新建连接。

1   ip被封

2   程序请求速度过快。

解决办法如下:

第一种方法 :

try:

      page1 = requests.get(ap)

except requests.exceptions.ConnectionError:

      r.status_code = "Connection refused"

第二种方法 :

1、增加重试连接次数     request的连接数过多而导致Max retries exceeded      在header中不使用持久连接

requests.adapters.DEFAULT_RETRIES = 5

2、关闭多余的连接   

s = requests.session()

s.keep_alive = False

或者   'Connection': 'close'

3、升级requests

pip install --upgrade requests

import requests

url='https://www.duitang.com/napi/blog/list/by_search/?kw=%E6%A0%A1%E8%8A%B1&start=0&limit=1000'

page=requests.get(url)

第三种方法 :

针对请求请求速度过快导致程序报错。

解决方法可以参考以下例子:

import time

while True:
    try:
        page = requests.get(url)
    except:
        print("Connection refused by the server..")
        print("Let me sleep for 5 seconds")
        print("ZZzzzz...")
        time.sleep(5)
        print("Was a nice sleep, now let me continue...")
        continue

代码运行后

SSLError: HTTPSConnectionPool(host='b-ssl.duitang.com', port=443):

 


 

Requests 可以为 HTTPS 请求验证 SSL 证书,就像 web 浏览器一样。SSL 验证默认是开启的,如果证书验证失败,Requests 会抛出 SSLError:

第一种解决方法:

 将verify 设置为 False,Requests 将忽略对 SSL 证书的验证

import requests

url='https://www.duitang.com/napi/blog/list/by_search/?kw=%E6%A0%A1%E8%8A%B1&start=0&limit=1000'

page=requests.get(url,verify=False)

具体见官方文档:SSL证书验证

 http://docs.python-requests.org/zh_CN/latest/user/advanced.html#ssl

第二种解决方法:

由于python2不支持SNI

具体SNI了解转:http://blog.csdn.net/makenothing/article/details/53292335

pip安装3个模块:

1.pyOpenSSL

2.ndg-httpsclient

3.pyasn1

 然后在使用requests请求前添加如下代码:

import urllib3.contrib.pyopenssl

urllib3.contrib.pyopenssl.inject_into_urllib3()

python 安装第三方库,超时报错--Read timed out.

# 解决方法,设置超时时间

pip --default-timeout=100 install -U Pillow

 

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐