简单的Web抓取PHP Xpath DOM

简单的Web抓取PHP Xpath DOM,php,dom,xpath,web-scraping,Php,Dom,Xpath,Web Scraping,我正在尝试学习网页抓取,并使用此示例从页面获取链接。是否有更好的方法,或者例如,获得h1的最简单方法是什么 $html = file_get_contents('page.html'); //parse the html into a DOMDocument $dom = new DOMDocument(); @$dom->loadHTML($html); //grab all the links on the page $xpath = new DOMXPath($dom); $hr

我正在尝试学习网页抓取,并使用此示例从页面获取链接。是否有更好的方法,或者例如,获得h1的最简单方法是什么

$html = file_get_contents('page.html');

//parse the html into a DOMDocument
$dom = new DOMDocument();
@$dom->loadHTML($html);

//grab all the links 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 "<br />Link: $url";

}
$html=file\u get\u contents('page.html');
//将html解析为文档
$dom=新的DOMDocument();
@$dom->loadHTML($html);
//抓取页面上的所有链接
$xpath=newdomxpath($dom);
$hrefs=$xpath->evaluate(“/html/body//a”);
对于($i=0;$i<$hrefs->length;$i++){
$href=$hrefs->item($i);
$url=$href->getAttribute('href');
echo“
链接:$url”; }
没有必要在你的外派人员前面加上
/html/body
/a
应该可以


另外,我会使用一个而不是for循环,但这主要是一种风格选择。

使用php的curl函数和domdocument,而不是file\u get\u内容进行刮取,这很简单而且功能强大