PHP 简单 HTML DOM 解析器,在没有类和 ID 的标签内查找文本

标签 php html dom html-parsing

我有一个 http://www.statistics.com/index.php?page=glossary&term_id=703

具体在这些部分:

<b>Additive Error:</b>
<p> Additive error is the error that is added to the true value and does not 
depend on the true value itself. In other words, the result of the measurement is 
considered as a sum of the true value and the additive error:   </p> 

我尽力获取标签 <p> 之间的文本和 </p> ,用这个:

include('simple_html_dom.php');
$url = 'http://www.statistics.com/index.php?page=glossary&term_id=703';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$curl_scraped_page = curl_exec($ch);
$html = new simple_html_dom();
$html->load($curl_scraped_page);

foreach ( $html->find('b') as $e ) {
echo $e->innertext . '<br>';
}

它给了我:

Additive Error:
Browse Other Glossary Entries

我尝试将 foreach 更改为:foreach ( $html->find('b p') as $e ) {

然后 foreach ( $html->find('/b p') as $e ) {

然后它就一直给我空白页。 我做错了什么? 谢谢。

最佳答案

为什么不使用 PHP 内置的 DOM 扩展和 xpath?

libxml_use_internal_errors(true);  // <- you might needs this if that page has errors
$dom = new DomDocument();
$dom->loadHtml($curl_scraped_page);
$xpath = new DomXPath($dom);
print $xpath->evaluate('string(//p[preceding::b]/text())');
//                             ^
//  this will get you text content from <p> tags preceded by <b> tags

如果有多个<p>标签前面有 <b>的,而您想只获取第一个,请将 xpath 查询调整为:

string((//p[preceding::b]/text())[1])

将它们全部作为 DOMNodeList , 省略 string()功能://p[preceding::b]/text()然后您可以遍历列表并访问 textContent每个节点的属性...

关于PHP 简单 HTML DOM 解析器,在没有类和 ID 的标签内查找文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17175575/

相关文章:

php - SilverStripe:如何向另一个网站发出 HTTP 请求?

PHP 黑名单检查器脚本

javascript - mootools 更改元素内联 css

javascript - 为什么 document.getElementsByClassName ("className")返回对象

javascript - 如何在reactjs中重建现有的Dom?

php - Woocommerce 运费基于特定运输类别的元素数量

php - Doctrine2 是否应用过滤器来删除语句

javascript - 使用 JavaScript 更改 <div> 类

javascript - 我的井字游戏 (jquery) 无法正常运行。丢失的零件无法正常工作

android - Jquery Mobile Listview 在 android 2.2.2 中不可滚动