【问题标题】:simple html dom parser can't get correct value简单的 html dom 解析器无法获得正确的值
【发布时间】:2015-05-10 11:19:18
【问题描述】:

我使用simple html dom parser抓取

include 'simple_html_dom.php';

function getSslPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

$html = getSslPage('http://forum.xda-developers.com/note-4-sprint');

$result = $html->find('.forumbox-header',0); //error here

echo $result;

我执行的输出将是 Sprint Samsung Galaxy Note 4,它具有 forumbox-header 类。我不知道我在那儿说Fatal error: Call to a member function find() on a non-object 时出错了。

【问题讨论】:

  • $result 是一个字符串,因为它从您请求的 URL 获取返回值。它不是一个对象。
  • 另外,鉴于提供的代码,看起来您根本没有真正使用简单的 html dom。附:也许使用内置的DOM functionality 也值得一看。
  • @JonStirling 你确定吗?当我回显 $html;我加载了请求的页面,而不是字符串。
  • 是的,很确定。试试var_dump($html);,将输出添加到您的问题中。
  • $result = curl_exec($ch); 返回字符串(html页面)。由于你得到一个字符串,你可以使用该库的str_get_html 函数。 $result = str_get_html($html);

标签: php web-scraping simple-html-dom


【解决方案1】:

您的getSslPage 函数返回一个string($url 页面的 html 源代码)。

虽然返回的值是一个字符串,但您将其视为对象$html->find,因此会出现错误。

致命错误:在非对象上调用成员函数 find()

Simple Html DOM Parser 库有 2 个函数来创建 DOM 对象:

  • file_get_html - 从 URL 创建一个 DOM 对象
  • str_get_html - 从字符串创建一个 DOM 对象

既然您已经有了 HTML 字符串,只需将您的代码编辑如下:

$html = str_get_html($html);
$result = $html->find('.forumbox-header',0);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 2012-01-17
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    相关资源
    最近更新 更多