【问题标题】:Finding div class value using php simple html dom or phpQuery使用 php simple html dom 或 phpQuery 查找 div 类值
【发布时间】:2013-03-28 14:21:37
【问题描述】:

我正在尝试掌握 php simple html dom,但在涉及 div 类时遇到了一些问题。

例如,假设在 newegg 上我想找到 div 类“skiplink”的值(我只是在网站上随机选择了一个类)。根据找到here 的php simple html dom 文档,我应该只使用。

$html = file_get_html('http://www.newegg.com');

print_r($ret = $html->find('.skiplink'));

现在它只是挂起并且似乎冻结了。我知道安装工作正常,因为以下代码有效。

foreach($html->find('a') as $element) 
   echo $element->href . '<br>';

基本上,我如何查看给定网站上的特定 div 类并找到该值?

有没有更简单的方法可以做到这一点,例如使用 phpQuery

【问题讨论】:

  • 你试过var_dump($html-&gt;find('.skiplink'));吗?
  • 为什么不直接使用DOMDocument ??
  • @AlfredXing chrome 在我尝试时崩溃了。
  • @Charlie 我将如何将它专门用于我正在尝试做的事情(查找给定 div 类的值)

标签: php html dom html-parsing


【解决方案1】:

通过在本网站上的简单搜索:How to get value from <div>value</div>?

但这就是他们所说的;

$doc = new DomDocument();
$doc->loadHTMLFile('http://www.results.com');
$thediv = $doc->getElementById('result');
echo $thediv->textContent;

或者你可以通过 id 获取它的值来找到你的 div 子句的 innerText 值;

$div = $doc->getElementById('result');
if($div) {
    echo $div->textContent;
}

【讨论】:

  • 我尝试的几乎所有事情都会出错。假设我想在 newegg 上找到 here 找到的商品的价格。它的 id 是 ltFrequentlyBoughtItemFinalPrice0 。当我使用您显示的代码时,我收到一堆错误,例如“警告:DOMDocument::loadHTMLFile() [domdocument.loadhtmlfile]: htmlParseEntityRef: expecting ';'”
【解决方案2】:

或者改用 XPath,这段代码会输出 src

//init DOMDocument
$dom = new DOMDocument();
//get the source from the URL
$html = file_get_contents("URL");
//load the html
dom->loadHTML($html);
//init XPath
$xpath = new DOMXPath($dom);

//fetch the src from the iframe within a class name
$iframe_src=$xpath->query('//*[@class="CLASSNAME"]/iframe//@src');

vardump($iframe_src);

要获取内容,请使用file_get_contents()

$options  = array('http' => array('user_agent' => 'USERAGENT')); //you must specify a user agent
$context  = stream_context_create($options);
$response = file_get_contents($iframe_src, false, $context);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-05
    • 2018-05-11
    • 2014-02-07
    • 1970-01-01
    • 2011-01-17
    相关资源
    最近更新 更多