V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
kisshere
V2EX  ›  程序员

PHP 写爬虫, curl_close 是不是不需要一直调用?

  •  
  •   kisshere · 2019-05-15 09:38:47 +08:00 · 1894 次点击
    这是一个创建于 1800 天前的主题,其中的信息可能已经有所发展或是发生改变。

    爬取各种页面:

    //page 1
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,PAGE_1_URL);
    curl_exec($ch);
    curl_close($ch);
    //然后爬取 page 2
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,PAGE_2_URL);
    curl_exec($ch);
    curl_close($ch);
    //然后爬取 page 3
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,PAGE_2_URL);
    curl_exec($ch);
    curl_close($ch);
    

    可不可以在代码开头写一个$ch = curl_init(); 所有页面爬完了再 curl_close($ch)?这样做是不是效率更高?

    5 条回复    2019-05-15 16:51:39 +08:00
    DavidNineRoc
        1
    DavidNineRoc  
       2019-05-15 09:48:35 +08:00
    这么简单的问题张口就来, 难不成你写一段代码不多块.


    想要效率高, curl 提供多线程.多个执行不需要引用返回值考虑用: curl_multi_exec
    benhuang1024
        2
    benhuang1024  
       2019-05-15 12:42:51 +08:00
    可以使用 Guzzle 软件包,进行异步,并发都挺不错
    单纯的单页或指定部分页面爬虫,毛遂自荐下 [MasterCloner/Cornerstone]( https://github.com/MasterCloner/Cornerstone)
    micookie
        3
    micookie  
       2019-05-15 14:11:15 +08:00
    Guzzle +1

    建议放弃 curl
    ritaswc
        4
    ritaswc  
       2019-05-15 14:54:36 +08:00
    放弃 curl 吧,时间宝贵
    NjcyNzMzNDQ3
        5
    NjcyNzMzNDQ3  
       2019-05-15 16:51:39 +08:00
    1.效率不会高。
    2.cli 情况下运行会内存溢出,应该一个请求就 close。
    3.curl 如果单进程单线程的话慢的很,可以试试 3L 的。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5181 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 01:22 · PVG 09:22 · LAX 18:22 · JFK 21:22
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.