Php 使用简单的HTMLDOM获取元素
我正在尝试获取网站中的所有菜单项。我试过的代码是Php 使用简单的HTMLDOM获取元素,php,simple-html-dom,Php,Simple Html Dom,我正在尝试获取网站中的所有菜单项。我试过的代码是 include("simple_html_dom.php"); $html = dlPage('http://www.homeshop18.com/'); $htmlpage=new simple_html_dom(); $htmlpage->load($html); $count=1; foreach($htmlpage->find('ul#nav') as $li){
include("simple_html_dom.php");
$html = dlPage('http://www.homeshop18.com/');
$htmlpage=new simple_html_dom();
$htmlpage->load($html);
$count=1;
foreach($htmlpage->find('ul#nav') as $li){
echo $count;
$count++;
}
ulnav中有10 li元素,但我得到的计数总是1。为什么?如果要遍历一组嵌套的ul元素,可以使用如下函数:
$html = file_get_html('http://www.homeshop18.com/');
$ulnav = $html->find('ul#nav', 0); // target the ul first
get_nested_lis( $ulnav );
function get_nested_lis( $ul ) {
# get the children of the ul element
foreach ($ul->children() as $li) {
# get the children of each of those li elements
foreach ($li->children() as $child) {
# if the element is an 'a', print the contents
if ($child->tag === 'a') {
# we have a link
echo "Link: " . $child->plaintext . "\n";
}
# if the element is another ul, call the function on that ul
elseif ($child->tag === 'ul') {
get_nested_lis( $child );
}
}
}
}
但是,您尝试遍历的页面上的菜单是由javascript生成的,因此,如果您要遍历该结构,您必须复制浏览器生成的源代码并在其上运行脚本。我正在执行一些任务,因此无法在回答中跟进,然而,你应该在你的问题中说明,你需要这些东西里面的东西。这就是为什么我早些时候回答了有关计数的问题。我将删除我的答案,因为你修改了你的问题。不管怎样,试试外星人的回答吧,我想你是想这么做的:nav li-如果你知道css,为什么应该是显而易见的。那么我如何才能得到浏览器生成的代码呢?我正在尝试使用cURL,我的方法正确吗?您需要从web浏览器复制并粘贴源代码。我需要将其自动化。无头浏览器会给我一个解决方案吗?