• 请不要在回答技术问题时复制粘贴 AI 生成的内容
kisshere
V2EX  ›  程序员

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

  •  
  •   kisshere · May 15, 2019 · 2682 views
    This topic created in 2582 days ago, the information mentioned may be changed or developed.

    爬取各种页面:

    //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 replies    2019-05-15 16:51:39 +08:00
    DavidNineRoc
        1
    DavidNineRoc  
       May 15, 2019
    这么简单的问题张口就来, 难不成你写一段代码不多块.


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

    建议放弃 curl
    ritaswc
        4
    ritaswc  
       May 15, 2019
    放弃 curl 吧,时间宝贵
    NjcyNzMzNDQ3
        5
    NjcyNzMzNDQ3  
       May 15, 2019
    1.效率不会高。
    2.cli 情况下运行会内存溢出,应该一个请求就 close。
    3.curl 如果单进程单线程的话慢的很,可以试试 3L 的。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   946 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 19:39 · PVG 03:39 · LAX 12:39 · JFK 15:39
    ♥ Do have faith in what you're doing.