使用 curl 进行 PHP 抓取 - 我该如何调试

标签 php curl screen-scraping

我几个小时前才知道什么是 scraping 和 cUrl,从那时起我就开始玩这个了。尽管如此,我现在面临着一些奇怪的事情。下面的代码适用于某些网站,但不适用于其他网站(当然我修改了 url 和 xpath ...)。请注意,当我测试 curl_exec 是否正确执行时,我没有引发任何错误。所以问题一定来自于之后的某个地方。我的一些问题如下:

  1. 如何检查新的 DOMDocument 是否正确创建:if(??)
  2. 如何检查新的 DOMDocument 是否已正确填充 html?
  3. ...如果创建了一个新的 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";
}

?>

最佳答案

使用 try/catch 检查文档对象是否已创建,然后检查 loadHTML() 的返回值以确定 HTML 是否已加载到文档中。您也可以在 XPath 对象上使用 try/catch。

try
{
    $dom = new DOMDocument();

    $loaded = $dom->loadHTML($html);

    if($loaded)
    {
        // loaded OK
    }
    else
    {
        // could not load HTML
    }
}
catch(Exception $e)
{
    // document could not be created, see $e->getMessage()
}

关于使用 curl 进行 PHP 抓取 - 我该如何调试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9666881/

相关文章:

php - 如何在多级对象属性访问中使用__get()返回null?

php - 在 PHP 中执行多个构造函数的最佳方法

python - 对于网站抓取库来说,Perl 或 Python 的良好起点是什么?

ruby - 是否可以使用 Nokogiri 创建 HTML 推送解析器?

Python - Beautiful Soup - 如何过滤提取的数据中的关键字?

php - Zendframework Rowset 按键选择

php - 对不同表中的相同字段进行排序

facebook - URL linter 不适用于 cURL

php - 如何从 url 获取图像的名称?

android - gcm 可以用于在 android 设备之间发送和接收消息吗?