使用過xpath來快速抓取頁面上的内容,可以使用谷歌浏覽器擴充來測試xpath表達式。
谷歌插件位址:https://chrome.google.com/webstore/detail/xpath-helper/hgimnogjllphhhkhlmebbmlgjoejdpjl
<?php
$html=file_get_contents('https://www.sogou.com/sogou?query=gif壓縮');
$dom = new DOMDocument();
//從一個字元串加載HTML
@$dom->loadHTML($html);
//使該HTML規範化
$dom->normalize();
//用DOMXpath加載DOM,用于查詢
$xpath = new DOMXPath($dom);
#擷取所有的a标簽的位址
$hrefs = $xpath->query("/html/body//a//@href");
for ($i = 0; $i < $hrefs->length; $i++) {
$href = $hrefs->item($i);
$linktext = $href->nodeValue;
echo $linktext;
echo "\r\n";
}
運作結果如下:
http://tool.apizl.com/dev/runCode/8d4b897a657b85744bd498d152ba8a31.html
文章位址:https://www.apizl.com/archives/view-134324-1.html