代码之家  ›  专栏  ›  技术社区  ›  Aleks Per

无法将loadHTMLfile或file\u get\u内容用于外部URL

  •  0
  • Aleks Per  · 技术社区  · 6 年前

    我想知道Groupon的活跃交易,所以我写了一个scraper,比如:

    libxml_use_internal_errors(true);
    
    $dom = new DOMDocument();
    @$dom->loadHTMLFile('https://www.groupon.com/browse/new-york?category=food-and-drink&minPrice=1&maxPrice=999');
    $xpath = new DOMXPath($dom);
    $entries = $xpath->query("//li[@class='slot']//a/@href");
    foreach($entries as $e) {
      echo $e->textContent . '<br />';
    }
    

    但是当我运行这个函数时,浏览器一直在加载,只是加载一些东西,但没有显示任何错误。

    我该怎么修?不仅仅是Groupon的情况-我也尝试其他网站,但也不工作。为什么?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Rancbar    6 年前

    使用CURL加载页面数据怎么样。

    Not just case with Groupon - I also try other websites but also don't work

    <?php
    
    $dom = new DOMDocument();
    $data = get_url_content('https://www.groupon.com', true);
    @$dom->loadHTML($data);
    $xpath = new DOMXPath($dom);
    $entries = $xpath->query("//label");
    
    foreach($entries as $e) {
        echo $e->textContent . '<br />';
    }
    
    
    function get_url_content($url = null, $justBody = true)
    {
    
        /* Init CURL */
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($ch, CURLOPT_HTTPHEADER, []);
        $data = curl_exec($ch);
        if ($justBody)
            $data = @(explode("\r\n\r\n", $data, 2))[1];
    
        var_dump($data);
        return $data;
    }