使用 javascript 从 google 搜索及其 URL 中获取第一个结果

Get first result from google search and its URL's with javascript

我有一段代码 return 是 URL 搜索;

        if (message.content.startsWith(prefix + "google")) {
        var lookup = message.content.replace(";google ", '');
        var newlookup = "https://www.google.com/search?source=hp&ei=mFopW5aMIomSsAfRw77IDg&q=test";
        newlookup = newlookup.replace('test',lookup);
        newlookup = newlookup.replace(/\s+/g, '+')
        message.channel.send("<a:googling:426453223310622740>" + " Loading...").then(r => {
             setTimeout(function(){
                r.edit(newlookup);
            }, 2000);
            });
    }

但我想要的是 return 我得到的第一个结果的 URL。例如,如果我搜索 "Whosebug",我会得到“https://whosebug.com/” 我不知道该怎么做。提前致谢

您可以使用

需要它然后你的代码应该是这样的:

const google = require("google");
//..................................................................................
message.channel.send("<a:googling:426453223310622740> Loading...").then(msg => {
  google(lookup, (err, res) => {
    if (err) console.error(err);
    else {
      let url = res.links[res.start].link; //you can also use .href instead of .link
      msg.edit(url);
    }
  });
});

这种方法很简单,但同时不是 "right" 方法:Google 不支持此包,如果您滥用它,他们可能会阻止您的搜索。我能找到的就这些了。

另一种方法是使用 Google 搜索 API,正如 André 所建议的,但这需要您创建自定义搜索引擎,并且您将无法浏览 google本身。