最近在学习 python 爬虫,写了个爬虫针对服务接口进行请求获取数据(单线程),在请求 1000+次之后服务器资源没有响应数据了,提示服务器连接池均在使用中;是使用 requests 库, post 方法请求之后将请求的内容保存成文件。求解求解
1
imn1 Jan 2, 2016
你先看看这边的机器是否也有大量连接没释放
1000+单线程,很少了,我觉得服务器限制的可能性更大 |
2
fsd010 OP @imn1 服务器那边无法接触到,这边代码上也没有做保持连接的做法,就默认 requests.post 就在这样
|
4
ratazzi PRO requests.post 这种用法就是没有使用连接池,并且没有断开,每次新开一个连接
|
7
Daniel65536 Jan 2, 2016
用 session , requests.Session()自带连接池,连接复用等等功能。
The Session object allows you to persist certain parameters across requests. It also persists cookies across all requests made from the Session instance, and will use urllib3 ‘ s connection pooling. So if you ’ re making several requests to the same host, the underlying TCP connection will be reused, which can result in a significant performance increase (see HTTP persistent connection). s = requests.Session() s.get('http://example.com/aaa') s.get('http://example.com/bbb') s.get('http://example.com/ccc') 这么用下去就好,方法、参数和 requests 一样。 |
8
fsd010 OP @Daniel65536 我问一下哈~如果按我原来的写法 requests.post 循环 1000 次,就建立 1000 个链接?如果采用 session 的方法可以复用链接不需重新建立连接?
|