我想返回谷歌搜索结果的第一个网址,例如: First Url Result
.php代码:
<?php
//Check if submit button is clicked or not
if (isset($_POST['submit'])) {
$text = $_POST['text'];
// echo $text;
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$query = $text;
$url = 'http://www.google.co.in/search?q='.urlencode($query).'';
echo $url;
$scrape = file_get_contents_curl($url);
echo $scrape;
?>
我怎样才能做到这一点?
最佳答案
默认情况下,由于使用此抓取方法仅发送 HTTP 请求,并且不会像浏览器那样运行渲染页面,因此 Google 不会加载您正在查找的页面,而是会向您显示类似这样的协议(protocol)页面。
您应该使用 ADyson 在评论中提到的 google Search API
不推荐的另一种方法是使用 selenium
或任何 headless 浏览器。使用 headless 浏览器,您仍然会收到协议(protocol)提示,但在其后面您可以抓取搜索结果。
关于php - 在 PHP 中返回 google 搜索的第一个结果的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68745333/