使用 PHP 中的 cURL 抓取源代码时出现问题


Problems by using cURL from PHP for scraping source code

我尝试从HTML数据表中自动下载以生成自定义报告。以下是我用 CURL 做的:

// init cURL HTTP Client 
$header = array(); 
$header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,"; 
$header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"; 
$header[] = "Cache-Control: max-age=0"; 
$header[] = "Connection: keep-alive"; 
$header[] = "Keep-Alive: 300"; 
$header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"; 
$header[] = "Accept-Language: en-us,en;q=0.5"; 
$header[] = "Pragma: "; 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7'); 
curl_setopt($ch, CURLOPT_HTTPHEADER, $header); 
curl_setopt($ch, CURLOPT_COOKIEFILE, '/.cookies'); 
curl_setopt($ch, CURLOPT_COOKIEJAR,  '/.cookies'); 
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
curl_setopt($ch, CURLOPT_FAILONERROR, TRUE); 
curl_setopt($ch, CURLOPT_HEADER, TRUE); 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 600); 
curl_setopt($ch, CURLOPT_URL, 'https:// ... /signin.html'); 
curl_setopt($ch, CURLOPT_POST, TRUE); 
curl_setopt($ch, CURLOPT_POSTFIELDS, "username=".$login."&password=".$pass); 
$response = curl_exec($ch);

登录工作正常,我可以毫无问题地获得许多页面。现在,我尝试通过以下方式获取数据表:

curl_setopt($ch, CURLOPT_URL, 'https:// ... /data.html'); 
curl_setopt($ch, CURLOPT_POST, FALSE); 
curl_setopt($ch, CURLOPT_POSTFIELDS, ''); 
$response = curl_exec($ch);

但是现在我得到了以下答案:

<html>
<head>
<script language='javascript'>function autoNavigate() {window.location="/data.html";}</script>
</head>
<body onload='autoNavigate()'></body>
</html>

javaScript 调用刷新与我之前加载的页面相同的页面。在浏览器中它工作正常,但是如果我再次使用"curl_exec($ch)"加载同一页面,我会遇到 302 错误?

是否有可能在没有完全重新加载的情况下用 curl 刷新页面?或者任何其他想法来获取页面的内容?

谢谢

尝试:

$postfields = '';
curl_setopt($ch, CURLOPT_URL, 'https:// ... /data.html'); 
curl_setopt($ch, CURLOPT_POST, TRUE); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields); 
$response = curl_exec($ch);

当您将 CURLOPT_POSTFIELDS 值设置为 false 时会产生问题,但之前您将其设置为 True ba,因为它在 Cookie 中保存了以前的详细信息。

我希望这对您有所帮助。

您是否检查了数据的链接.html?
如果数据.html window.location="data.html";是数据的位置相同.html curl_setopt($ch, CURLOPT_URL, 'https:// ... /data.html');尝试加倍curl_exec($ch)因此可能需要访问两次。或者,如果它不同,只需更改您的链接即可。