除了标题之外,还可以获取谷歌搜索结果的URL和描述


Get URLs and descriptions of Google search results in addition to titles

我写了这段代码——一个谷歌搜索结果解析器——但它只得到标题:

$url = "http://www.google.com/search?client=opera&q=example&sourceid=opera&ie=UTF-8&oe=UTF-8";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, $timeout);
$html = curl_exec($ch);
curl_close($ch);
$dom = new DOMDocument();
@$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('h3') as $link) {
    echo $link->nodeValue;
    echo "<br />";
}

如何获取URL和描述?

您可以获得链接名称和类似的url

示例:

<?php
$url = "http://www.google.com/search?client=opera&q=example&sourceid=opera&ie=UTF-8&oe=UTF-8";
$ch = curl_init();
$timeout = 5;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, $timeout);
$html = curl_exec($ch);

curl_close($ch);
$dom = new DOMDocument();
@$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('h3') as $link) {
    echo $link->nodeValue."'n";
    echo str_replace('/url?q=', '',$link->firstChild->getAttribute('href'))."'n";
    echo "<br />";
}