【问题标题】:loop through divs and extract text using simplehtmldom循环遍历 div 并使用 simplehtmldom 提取文本
【发布时间】:2012-12-10 20:25:55
【问题描述】:

我正在使用 simplehtmldom 从站点中获取 html。然后我搜索页面上的所有 div 并 显示字数大于 300 的内部文本。为此,我使用 foreach 进行迭代。

$findDivs = $html->find('div');

foreach($findDivs as $findDiv) {
  $wordCount = explode(' ', $findDiv->outertext);
  $wordCount = count($wordCount);
  if($wordCount <= 300) {
    $findDiv->outertext = '';
   }
   else {
     echo $findDiv->outertext . '<br />';
  }
}

我遇到的问题是结果重复了 6 次。我只能假设这是因为每次迭代都会循环所有 div。但是,我不确定我可以使用什么技术来确保每个 div 只被评估一次。

【问题讨论】:

  • 递归迭代 div,如果 div 包含超过 300 个单词,则不处理 div 的子级。
  • 请提供示例 html。否则你不太可能得到建设性的帮助。

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


【解决方案1】:

您想要innertext,但您的代码声明outertext - 我认为这是重复的原因。

foreach($html->find('div') as $findDiv) {
  $wordCount = explode(' ', $findDiv->innertext);
  $wordCount = count($wordCount);
  if($wordCount > 300) {
    echo $findDiv->outertext . '<br />';
   }
}

【讨论】:

  • 嗨大卫,谢谢你,但恐怕我尝试了内文、外文和明文,每次重复的结果都是一样的。
【解决方案2】:

我不知道为什么,但这解决了我的问题。

我在 $html->find('div',1); 中添加了 '1' 参数

所以工作代码如下:

$findDivs = $html->find('div',1);  //add a 1 to the divs. this works as the script now only loops once.

foreach($findDivs as $findDiv) {
  $wordCount = explode(' ', $findDiv->outertext);
  $wordCount = count($wordCount);
  if($wordCount <= 300) {
    $findDiv->outertext = '';
   }
   else {
     echo $findDiv->outertext . '<br />';
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 2014-07-02
    • 1970-01-01
    相关资源
    最近更新 更多