![](/img/trans.png)
[英]Find div that has no class and no id in PHP Simple HTML DOM Parser
[英]PHP Simple HTML DOM Parser, find text inside tags that have no class nor id
我有一個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
如果<b>
之前有多個<p>
標記,而您只想獲得第一個,則將xpath查詢調整為:
string((//p[preceding::b]/text())[1])
要將它們全部作為DOMNodeList
,請省略string()
函數: //p[preceding::b]/text()
,然后可以遍歷列表並訪問每個節點的textContent
屬性...
如果您希望所有內容都位於b或p標簽內,則可以簡單地執行foreach ($html->find('b,p') as $e) { ... }
。
嘗試這個
<?php
$dom = new DOMDocument();
@$dom->loadHTMLFile('http://www.statistics.com/index.php?page=glossary&term_id=703');
$xpath = new DOMXPath($dom);
$mytext = '';
foreach($xpath->query('//font') as $font){
$mytext = $xpath->query('.//p', $font)->item(0)->nodeValue;
break;
}
echo $mytext;
?>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.