gpt4 book ai didi

javascript - 如何使用 php DOM 从 html 页面获取特定链接?

转载 作者:行者123 更新时间:2023-11-28 06:44:35 25 4
gpt4 key购买 nike

我使用此代码获取 html 页面中的所有链接,效果很好。

<?php
$html = file_get_contents('http://realestate.com.kh/real-estate-for-sale-in/all/');

$dom = new DOMDocument();
@$dom->loadHTML($html);

// grab all the on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {
$href = $hrefs->item($i);
$url = $href->getAttribute('href');
echo $url.'<br />';
}
?>

但我只想从 div 或类中获取特定链接,就像这样

<ul class="menu">
<li><a href="#">product1</li>
<li><a href="#">product2</li>
<li><a href="#">product3</li>
<li><a href="#">product4</li>
</ul>

那么我怎样才能将类提供给上面的代码,以便我只能获取菜单类中的链接。

非常感谢您帮我解决这个问题。

最佳答案

你应该能够做到

$xpath->query('/html/body/ul[contains(@class,"menu")]/a');

参见:PHP DOM Xpath - search for class name

关于javascript - 如何使用 php DOM 从 html 页面获取特定链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33502835/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com