【问题标题】:PHP Simple HTML DOM Parser: how to get contents of the parent div containing <h1> tags?PHP Simple HTML DOM Parser:如何获取包含 <h1> 标签的父 div 的内容?
【发布时间】:2014-10-09 22:18:33
【问题描述】:

我正在抓取(使用 PHP 简单的 HTML DOM)许多不同的(新闻)网站,目的是获取页面上的主要内容/文本主体。

要做到这一点,我能想到的最好方法是找到主标题/标题 (H1) 并将文本包含在与此标题标签相同的 div 中。

在下面的两个示例中,我将如何获取整个(父?) div 的内容。

<div>  <----- need to get contents of this whole div (containing the h1 and likely the main body of text)
  <h1></h1>
  main body of text here
</div>

Div 可能在树的上方。

<div> <----- need to get contents of this whole div
  <div>   
    <h1></h1>
  </div>

  <div>
    main body of text here
  </div>
</div>

在树的上方进一步划分。

<div> <----- need to get contents of this whole div
  <div>

    <div>   
      <h1></h1>
    </div>

    <div>
      main body of text here
    </div>

  </div>
</div>

然后我可以比较每个的大小,并确定主 div。

【问题讨论】:

  • 澄清一下,你用的是这个? simplehtmldom.sourceforge.net
  • @slapyo 是的,使用 simplehtmldom.sourceforge.net
  • PS:没有&lt;text&gt;这样的html元素。
  • “比较每个的大小,确定主div”是什么意思?您是否考虑过如何以编程方式确定哪个div 是“主要”div
  • 你想要最高的gparent div?在 jQuery 和 this one 中,它是第一个 $('div:has(h1)')。 Simple 做不到。

标签: php web-scraping simple-html-dom simpledom


【解决方案1】:

可以使用parent获取h1的父元素:

# assuming that the <h1> element is the first <h1> on the page:
$div = $html->find('h1', 0)->parent();

【讨论】:

    【解决方案2】:

    假设 $e 包含您选择的 H1 元素。你可以调用 $e->parent() 来抓取父元素。

    查看“如何遍历 DOM 树?”在“遍历 DOM 树”选项卡上。 http://simplehtmldom.sourceforge.net/manual.htm

    【讨论】:

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