3

尽管使用了 FOLLOWLOCATION 和 MAXREDIRS,但我收到 301 错误。我不知道该怎么做,我尽我所能:HEADER 为 0,FOLLOWLOCATION 为 1,MAXREDIRS 为 30,多次更改 USERAGENT,单独使用 COOKIEFILE,然后使用 COOKIEJAR,但没有。

这是最奇怪的部分:我试图抓取的同一个网站不会为其他页面提供 301,只是针对某些页面。有任何想法吗??

function curl_start($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.4");
curl_setopt($ch, CURLOPT_REFERER, "http://google.com/");
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_ENCODING, "gzip");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
$html = curl_exec($ch);
curl_close($ch);
return $html;
}
4

2 回答 2

0

除非您在安全模式下运行 php,否则它应该可以工作。但即使这对你来说也不是问题。

无论如何,试试这个。

<?php
function curl_redirect_exec($ch, &$redirects, $curlopt_header = false) {
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    if ($http_code == 301 || $http_code == 302) {
        list($header) = explode("\r\n\r\n", $data, 2);
        $matches = array();
        preg_match('/(Location:|URI:)(.*?)\n/', $header, $matches);
        $url = trim(array_pop($matches));
        $url_parsed = parse_url($url);
        if (isset($url_parsed)) {
            curl_setopt($ch, CURLOPT_URL, $url);
            $redirects++;
            return curl_redirect_exec($ch, $redirects);
        }
    }
    if ($curlopt_header)
        return $data;
    else {
        list(,$body) = explode("\r\n\r\n", $data, 2);
        return $body;
    }
}
?>

SRC:http ://www.php.net/manual/en/function.curl-setopt.php#95027

于 2012-12-27T13:00:09.670 回答
0

您的代码在我的服务器上运行。所以我想它与safe_modeopen_basedir已设置有关。您可以通过使用 启动脚本来检查输出警告error_reporting(E_ALL);。它应该显示警告。

检查以下链接以查看解决方案。

http://php.net/manual/ro/function.curl-setopt.php#102121

于 2012-12-27T13:23:13.547 回答