php使用xpath来进行采集页面的内容

作者:apizl 来源:www.apizl.com 更新时间:2023-05-25 21:55

使用过xpath来快速抓取页面上的内容,可以使用谷歌浏览器扩展来测试xpath表达式。

 

谷歌插件地址:https://chrome.google.com/webstore/detail/xpath-helper/hgimnogjllphhhkhlmebbmlgjoejdpjl

 

php使用xpath来进行采集页面的内容

我们来获取页面上所有的A标签href内容,具体其他表达式可以在谷歌插件上进行测试。

如下就是使用php用xpath表达式来获取内容!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?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";
}

php使用xpath来进行采集页面的内容

运行结果如下:

 

http://tool.apizl.com/dev/runCode/8d4b897a657b85744bd498d152ba8a31.html

 

php使用xpath来进行采集页面的内容