我刚刚知道什么scrapping和cUrl是在几个小时前,从那以后我玩了。尽管如此,我现在面临一些奇怪的事情。下面的代码可以在一些网站上正常工作,而不是与其他网站一起工作(当然我修改了url和xpath ...)。请注意,当我测试curl_exec是否正确执行时,我没有提出错误。所以这个问题必须来自某个地方。我的一些问题如下:PHP刮擦卷曲 - 我如何调试
- 我如何检查,如果新的DOM文档已正确创建:如果(??)
- 我如何检查新的DOMDocument已经与HTML正确填充?
- ...如果创建了新的DOMXPath对象?
希望我很清楚。预先感谢您的回复。干杯。马克
我的PHP:
<?php
$target_url = "http://www.somesite.com";
$userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)';
// make the cURL request to $target_url
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html= curl_exec($ch);
if (!$html) {
echo "<br />cURL error number:" .curl_errno($ch);
echo "<br />cURL error:" . curl_error($ch);
exit;
}
// parse the html into a DOMDocument
$dom = new DOMDocument();
@$dom->loadHTML($html);
// grab all the on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->query('somepath');
for ($i = 0; $i < $hrefs->length; $i++) {
$href = $hrefs->item($i);
$url = $href->getAttribute('href');
echo "<br />Link: $url";
}
?>
+1对于不使用reg-ex“解析”HTML。为了检测错误,请检查['DOMDocument :: loadHTML()'](http://www.php.net/manual/en/domdocument.loadhtml.php)的相应返回值,并可能删除抑制运算符' @'。 – 2012-03-12 12:24:18
你好Linus。感谢您的帮助。你能帮我一下语法吗?应该是:if(DOMDocument :: loadHTML($ html){} else {})? – Marc 2012-03-12 12:32:18
你也可以通过探测HTTP响应代码来扩展你的“did-curl-execute”检查(这是通过['curl_getinfo()']完成的(http://php.net/manual/en/function.curl-getinfo .php)并使用'CURLINFO_HTTP_CODE')成功执行'curl_exec()'后。 – 2012-03-12 13:11:19