V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
fsd010
V2EX  ›  Python

python 爬虫释放资源相关问题

  •  
  •   fsd010 · 2016-01-02 15:30:48 +08:00 · 3295 次点击
    这是一个创建于 3045 天前的主题,其中的信息可能已经有所发展或是发生改变。
    最近在学习 python 爬虫,写了个爬虫针对服务接口进行请求获取数据(单线程),在请求 1000+次之后服务器资源没有响应数据了,提示服务器连接池均在使用中;是使用 requests 库, post 方法请求之后将请求的内容保存成文件。求解求解
    8 条回复    2016-01-02 17:21:19 +08:00
    imn1
        1
    imn1  
       2016-01-02 15:37:55 +08:00
    你先看看这边的机器是否也有大量连接没释放
    1000+单线程,很少了,我觉得服务器限制的可能性更大
    fsd010
        2
    fsd010  
    OP
       2016-01-02 15:47:21 +08:00
    @imn1 服务器那边无法接触到,这边代码上也没有做保持连接的做法,就默认 requests.post 就在这样
    imn1
        3
    imn1  
       2016-01-02 15:50:10 +08:00
    @fsd010
    不是审视代码,是在路由器或者其他工具,看看连接数
    ratazzi
        4
    ratazzi  
       2016-01-02 16:16:53 +08:00
    requests.post 这种用法就是没有使用连接池,并且没有断开,每次新开一个连接
    fsd010
        5
    fsd010  
    OP
       2016-01-02 16:42:12 +08:00
    @imn1 刚刚试验下, ctrl+c 没有中断连接,还保持,重启进程链接流量继续传输,可能传输的容量有限制,循环累积下很大就报错,线程不多就一个
    fsd010
        6
    fsd010  
    OP
       2016-01-02 16:43:23 +08:00
    @ratazzi 那是得每次请求后中断连接?还是指一个进程就一个链接?
    Daniel65536
        7
    Daniel65536  
       2016-01-02 16:53:17 +08:00
    用 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 一样。
    fsd010
        8
    fsd010  
    OP
       2016-01-02 17:21:19 +08:00
    @Daniel65536 我问一下哈~如果按我原来的写法 requests.post 循环 1000 次,就建立 1000 个链接?如果采用 session 的方法可以复用链接不需重新建立连接?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   772 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 20:26 · PVG 04:26 · LAX 13:26 · JFK 16:26
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.