【问题标题】:Return the Link of first result in google search in PHP在 PHP 中返回 google 搜索中第一个结果的链接
【发布时间】:2021-08-12 02:30:43
【问题描述】:

我想返回 google 搜索结果的第一个 URL,例如: 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;
?>

我怎样才能做到这一点?

【问题讨论】:

  • 你没有说上面代码的结果是什么,但谷歌通常不喜欢你试图抓取他们的搜索页面,你可能会发现它在某些情况下被阻止/混淆/不可用来自 cURL 请求的方式。改用他们的搜索 API。

标签: php google-search


【解决方案1】:

默认情况下,由于使用这种抓取方法只发送一个 HTTP 请求并且不会像浏览器那样运行渲染页面,谷歌不会加载你正在寻找的页面,它会向你显示一个这样的协议页面。

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

另一种不推荐的方法是使用selenium 或任何无头浏览器。使用无头浏览器,您仍然会收到协议提示,但在它背后您可以抓取搜索结果。

【讨论】:

    猜你喜欢
    • 2013-07-03
    • 2021-12-01
    • 2020-06-24
    • 2011-09-22
    • 2021-10-28
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    相关资源
    最近更新 更多