获取指定URL页面中的所有链接

回复 星标
更多
«
获取指定URL页面中的所有链接
»
-
-

以下代码可以获取到指定URL页面中的所有链接,即所有a标签的href属性:

// 获取链接的HTML代码

$html = file_get_contents('http://www.example.com');

$dom = new DOMDocument();

@$dom->loadHTML($html);

$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 />';

}

这段代码会获取到所有a标签的href属性,但是href属性值不一定是链接,我们可以在做个过滤,只保留http开头的链接地址:

// 获取链接的HTML代码

$html = file_get_contents('http://www.example.com');

$dom = new DOMDocument();

@$dom->loadHTML($html);

$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');

// 保留以http开头的链接

if(substr($url, 0, 4) == 'http')

echo $url.'<br />';

}

新窗口打开 关闭