使用simple_html_dom.php找不到元素


Cannot find element using simple_html_dom.php

这是我正在使用的脚本:

<?php
    include_once("simple_html_dom.php");
    $html = file_get_html("http://www.amazon.com/gp/product/B000VS8CTM");
    $title = $html->find('#title');
    echo count($title);
?>

count($title)返回0。

网页上确实有一行

<h1 id="title" class="a-size-large a-spacing-none">Folding Helping Hand Long-Reach Pick-Up Gripper - 26" Aluminum</h1>

但是simple_html_dom脚本找不到它。

我也试过

$title = $html->find('h1[id=title]');

但是count($title)仍然返回0。

我运行

echo $html->plaintext;

标题就在那里。

我不知道问题出在哪里。

感谢您的帮助!


编辑:

我注意到stackoverflow在我保存帖子后不知怎么更改了我的url。

这是正确的函数调用:file_get_html("http://www.amazon.com/gp/product/B000VS8CTM").

这将为您提供标题。尝试:

<?php
    include_once("simple_html_dom.php");
    $html = new simple_html_dom();
    $html->load_file("http://rads.stackoverflow.com/amzn/click/B000VS8CTM");
    $title = $html->find('h1',0);
    $title = $title->find('#btAsinTitle',0);
    echo $title->innertext;
?>

试试这个:

<?php
$url = "http://www.amazon.com/gp/product/B000VS8CTM";
include_once("simple_html_dom.php");
$_curl = curl_init();
curl_setopt($_curl, CURLOPT_SSL_VERIFYHOST, 1);
curl_setopt($_curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($_curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($_curl, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; InfoPath.1)');
curl_setopt($_curl, CURLOPT_URL, $url);
$html = curl_exec( $_curl );
$_htmlDom = new simple_html_dom();
$_htmlDom->load(  $html  );
$productTitle = $_htmlDom->find('h1#title', 0)->innertext;
$str = $_htmlDom->save();
var_dump($str); //return string length: 400946, refer to Remark 1
$_htmlDom->clear();
var_dump($productTitle);
?>

备注1:

我也用follow代码进行了测试,肯定有不同的地方,但我没有跟踪细节。

总结结果:

  • 使用cURL必须使用CURLOPT_RETURNTTRANSFER
  • 使用_htmlDom->load_file有时会丢失一些内容

编码:

<?php
$_htmlDom = new simple_html_dom();
$_htmlDom->load_file(  $url  ); // or get HTML from SimpleHtmlDom
$productTitle = $_htmlDom->find('h1#title', 0)->innertext;
var_dump($productTitle); //return NULL
$str = $_htmlDom->save();
var_dump($str); //return string length: 283459
$_htmlDom->clear();
?>

您可以使用foreach()循环以这种方式使用:

include_once("simple_html_dom.php");
$html = file_get_html("http://rads.stackoverflow.com/amzn/click/B000VS8CTM");
foreach($html->find('h1') as $element) 
{
    echo $element->plaintext;
}

我刚刚通过将其放入文件来解决类似的问题

ini_set('user_agent', 
  'Mozilla/5.0 (Windows; U; Windows NT 6.0; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3');

本网站信用:http://www.electrictoolbox.com/php-change-user-agent-string/