【问题标题】:Cant use loadHTMLfile or file_get_contents for external URL不能对外部 URL 使用 loadHTMLfile 或 file_get_contents
【发布时间】:2018-12-12 13:02:09
【问题描述】:

我想知道 Groupon 的活跃交易,所以我写了一个像这样的爬虫:

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 的情况——我也尝试过其他网站,但也不起作用。为什么?

【问题讨论】:

  • @$dom 中使用@ 将抑制加载URL 时出现的任何错误,将其删除,您可能会看到发生了什么。
  • 我删除它但浏览器再次加载并且不停止
  • 也许他们有一个您可以使用的 api,可能是因为他们不希望您抓取他们的页面,也许您可​​以欺骗浏览器代理或 cookie 或其他东西,但我建议使用api 代替

标签: php dom xpath file-get-contents


【解决方案1】:

如何使用 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;
}

【讨论】:

  • 我无法加载任何网站,这很奇怪
  • 我猜这是因为 Apache 配置错误。也许重新安装 Apache [或其他 http 服务器] 可以解决您的问题,或者在另一台机器上测试它
  • 嗯,不,我在尝试过多次后收到了这条消息:file_get_contents(groupon.com/browse/…): failed to open stream: HTTP request failed! HTTP/1.0 403 禁止
猜你喜欢
  • 2014-08-28
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 2016-03-27
  • 2017-03-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多