如何获取$html->find('section[class="default-match-block"]')返回元素的数量?
如何获取simple_html_dom中匹配元素的数量?
嘿,我来帮你搞定这个问题~在使用simple_html_dom的PHP爬虫场景里,要获取$html->find('section[class="default-match-block"]')返回的元素数量其实非常简单,核心思路是利用PHP内置的count()函数,因为find()方法返回的是一个包含匹配元素的数组。
具体实现步骤:
- 先存储匹配结果:把
find()的返回值赋值给一个变量,这样既可以用来后续遍历处理,又能避免重复调用find()解析DOM(提升代码效率)。 - 用count()统计数量:直接对这个变量使用
count()函数,得到的就是匹配到的元素总数。
结合你的代码修改示例:
下面是在你提供的爬虫代码中添加统计元素数量的完整版本:
<?php include_once('../simple_html_dom.php'); function scraping_IMDB($url) { // create HTML DOM $html = file_get_html($url); // get title $ret['Title'] = $html->find('title', 0)->innertext; // get rating $ret['Game Title'] = $html->find('div[class="match-section-head"]', 0)->plaintext; // 1. 获取所有匹配的section元素并存储到变量 $matchSections = $html->find('section[class="default-match-block"]'); // 2. 统计元素数量并加入返回数组 $ret['Match Block Count'] = count($matchSections); // 遍历处理每个匹配元素 foreach($matchSections as $div) { $ret['Name'] = $div->find('a',0)->innertext; print $ret['Name'].'<br />'; } // clean up memory $html->clear(); unset($html); return $ret; } // test it! $ret = scraping_IMDB('http://www.example.com'); foreach($ret as $k=>$v) echo '<strong>'.$k.' </strong>'.$v.'<br>'; ?>
额外小提示:
如果只是单纯需要获取数量而不需要遍历元素,也可以直接写成:
$count = count($html->find('section[class="default-match-block"]'));
不过还是更推荐先把匹配结果存到变量里,因为重复调用find()会重复解析DOM树,多做不必要的工作哦~
内容的提问来源于stack exchange,提问作者Shubham Sejpal
相关产品推荐
相关产品推荐

