今天写Python网络爬虫的时候遇到一个问题,报错的具体内容如下:

HTTPConnectionPool(host='dds.cr.usgs.gov', port=80): Max retries exceeded with url: /ltaauth//sno18/ops/l1/2016/138/037/LC81380372016038LGN00.tar.gz?id=stfb9e0bgrpmc4j9lcg45ikrj1&iid=LC81380372016038LGN00&did=227966479&ver=production (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 65] No route to host',))1

多方查阅后发现了解决问题的原因:http连接太多没有关闭导致的。

解决办法:

1、增加重试连接次数

requests.adapters.DEFAULT_RETRIES = 5

2、关闭多余的连接

requests使用了urllib3库,默认的http connection是keep-alive的,requests设置False关闭。

操作方法

s = requests.session()
s.keep_alive = False

请参考 http://xiaorui.cc/2017/04/03/%E6%9E%84%E5%BB%BA%E9%AB%98%E6%95%88%E7%9A%84python-requests%E9%95%BF%E8%BF%9E%E6%8E%A5%E6%B1%A0/

找到的另外一个方法,不提示错误了

res = requests.session()
res.proxies = proxies
res = requests.get("https://www.baidu.com/",timeout=10)

HTTPX 基础教程-新乡seo|网站优化,网站建设_微信公众号:zeropython—昊天博客