【问题标题】:403 error when using file_get_contents()使用 file_get_contents() 时出现 403 错误
【发布时间】:2014-03-29 17:14:48
【问题描述】:

我正在尝试使用以下代码从网站上抓取一些产品详细信息:

$list_url = "http://www.topshop.com/en/tsuk/category/sale-offers-436/sale-799";
$html = file_get_contents($list_url);
echo $html;

但是,我收到了这个错误:

警告: file_get_contents(http://www.topshop.com/en/tsuk/category/sale-offers-436/sale-799) [function.file-get-contents]:无法打开流:HTTP 请求 失败的! HTTP/1.0 403 禁止在 /homepages/19/d361310357/htdocs/shopaholic/rss/topshop_f_uk.php 上 第 123 行

我认为这是网站为防止抓取而设置的某种屏蔽。有没有办法解决这个问题 - 也许使用 cURL 并设置用户代理?

如果没有,是否有其他方法可以获取商品名称和价格等基本产品数据?

编辑

我的代码上下文是我最终仍然希望能够实现以下目标:

$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);

【问题讨论】:

    标签: php web-scraping http-status-code-403


    【解决方案1】:

    我已经设法通过添加以下代码来修复它...

    ini_set('user_agent','Mozilla/4.0 (compatible; MSIE 6.0)');
    

    ...根据this answer

    【讨论】:

      【解决方案2】:

      您应该使用 cURL,而不是使用 file_get_contents() 的简单方法。
      使用 cURL 并设置正确的 http 标头来模拟正确的 http 请求(真实请求)。

      附: : 设置 cURL 以跟随重定向。这是cURL的链接

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-07-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-14
        • 2018-12-28
        • 2017-09-04
        相关资源
        最近更新 更多