我使用此代码获取 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');
关于javascript - 如何使用 php DOM 从 html 页面获取特定链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33502835/