【发布时间】:2012-03-28 20:11:41
【问题描述】:
我几个小时前才知道什么是报废和 cUrl,从那时起我就开始玩了。尽管如此,我现在面临着一些奇怪的事情。下面的代码适用于某些网站而不适用于其他网站(当然我修改了 url 和 xpath ...)。请注意,当我测试 curl_exec 是否正确执行时,我没有出现错误。所以问题一定来自之后的某个地方。我的一些问题如下:
- 如何检查新的 DOMDocument 是否已正确创建:if(??)
- 如何检查新的 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 不使用正则表达式“解析”HTML。为了检测错误,请检查
DOMDocument::loadHTML()的相应返回值,并可能删除抑制运算符@。 -
你好莱纳斯。感谢您的帮助。你能帮我看看语法吗?应该是:if(DOMDocument::loadHTML($html) {}else{}) 吗?
-
您还可以通过在成功的
curl_exec()之后探测 HTTP 响应代码(这是通过curl_getinfo()并使用CURLINFO_HTTP_CODE完成的)来扩展您的“did-curl-execute”检查。跨度> -
在我的代码正常工作和不工作的两个站点中,curl_getinfo() 返回代码 200,表示正常。所以问题出在其他地方。这开始让我发疯了....
-
@LinusKleen - 我在 curl_execution 后回显后检查了 html 源代码,似乎每行之间都有一个小“段落图标”(请参阅我在主帖中所做的编辑)你认为这可能是原因吗?
标签: php curl screen-scraping