【问题标题】:Stuck on traversing a html dom on a page停留在遍历页面上的 html dom
【发布时间】:2017-08-02 00:13:38
【问题描述】:

好的。我再次陷入困境,似乎互联网刚刚用完 HTML DOM 教程遍历 dom。我有这个页面(http://www.nasdaqomxbaltic.com/market/?pg=news&news_id=250910),我想要做的是将文本The statement of shareholders for shares sale and for shares purchase attached. 和附件放入一个变量中。我正在尝试以最有效的方式做到这一点,所以我没有使用 simple_html_dom。如果我有选择或者它会更快,我不会使用 xpath,但我不确定:)

编辑:尝试了 Phil 的代码。似乎无法弄清楚为什么它仍然不起作用。

   <?
$dom = new DOMDocument();
@$dom->loadHTMLFile("http://www.nasdaqomxbaltic.com/market/?pg=news&news_id=250910");

$xpath = new DOMXPath($dom);
$paragraph = $xpath->query('//table[@id="previewTable"]/tbody/tr[2]/td/p');//tried removing tbody, doesn't fix, why is it there?
if ($paragraph->length == 1) {//what is this?
     $sentence = $paragraph->nodeValue;
    print_r($sentence);//doesnt work (blank)
}
$links = $xpath->query('//table[@id="previewTable"]//td[@class="tdAttachment"]//a');
foreach ($links as $link) {
    $linkName = $link->nodeValue;
    $linkUrl = $link->getAttribute('href');
echo $linkName;
echo $linkUrl;//works
}
?>

【问题讨论】:

  • 不——它不能那样工作
  • 你不需要file_get_contents(),只需使用DOMDocument::loadHTMLFile()

标签: php html dom traversal


【解决方案1】:

这实际上取决于该标记的固定程度。

假设结构是相当静态的,检索句子,尝试

$paragraphs = $xpath->query('//table[@id="previewTable"]/tr[2]/td/p');
if ($paragraphs->length > 0) { // check to make sure we got at least one node
    $sentence = $paragraphs->item(0)->nodeValue;
}

检索链接稍微复杂一些

$links = $xpath->query('//table[@id="previewTable"]//td[@class="tdAttachment"]//a');
foreach ($links as $link) {
    $linkName = $link->nodeValue;
    $linkUrl = $link->getAttribute('href');

    // do something with these values
}

【讨论】:

  • @Josh 我的错,我忘了拿到第一段。还删除了tbody,不应该使用 DOM 检查器来读取源代码。更新了我的答案
  • 太棒了!这完美地工作。是否有用于获取例如 //table[@id="previewTable"] 标记的来源的 html dom 方法? (我的意思是除了这个表标签之外的所有标签)。
  • @Josh Google "php dom innerhtml"
猜你喜欢
  • 2013-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-14
  • 1970-01-01
  • 2013-06-07
  • 2015-07-13
相关资源
最近更新 更多