php - 在 PHP 中返回 google 搜索的第一个结果的链接

标签 php google-search

我想返回谷歌搜索结果的第一个网址,例如: First Url Result

Google search

.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)页面。 enter image description here

您应该使用 ADyson 在评论中提到的 google Search API

不推荐的另一种方法是使用 selenium 或任何 headless 浏览器。使用 headless 浏览器,您仍然会收到协议(protocol)提示,但在其后面您可以抓取搜索结果。 enter image description here

关于php - 在 PHP 中返回 google 搜索的第一个结果的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68745333/

相关文章:

java - 使用 Java 获取 google searchResultTime

indexing - 从谷歌搜索中完全排除目录

php - 复选框数组只返回一个结果

php - 为什么我的 php 代码不能执行任何操作?

php - 使用 php 和 mysql 的产品网站

php - php比较字符串的方法

seo - Google 是否会惩罚来 self 的裸域的 301 重定向?

python - 如何使用 python 在谷歌搜索中提取描述?

seo - 使 Durandal SPA 网站 SEO 友好

php - SQL、PHP、子查询