Google 为授权搜索提供了一个 API,所以不要大惊小怪地抓取网页。
例如,您可以将Custom Search API 与UrlFetch() 一起使用。
从脚本编辑器转到Resources -> Developer's Console Project... -> View Developer's Console。为公共 API 访问创建一个新密钥。按照自定义搜索 API 文档中的说明创建自定义搜索引擎。将密钥和 ID 输入脚本中指示的位置。 (下面有更多详细信息。)
此示例脚本将返回一个包含成功搜索结果的对象;您可以导航对象以提取您想要的任何信息。
/**
* Use Google's customsearch API to perform a search query.
* See https://developers.google.com/custom-search/json-api/v1/using_rest.
*
* @param {string} query Search query to perform, e.g. "test"
*
* returns {object} See response data structure at
* https://developers.google.com/custom-search/json-api/v1/reference/cse/list#response
*/
function searchFor( query ) {
// Base URL to access customsearch
var urlTemplate = "https://www.googleapis.com/customsearch/v1?key=%KEY%&cx=%CX%&q=%Q%";
// Script-specific credentials & search engine
var ApiKey = "--get from developer's console--";
var searchEngineID = "--get from developer's console--";
// Build custom url
var url = urlTemplate
.replace("%KEY%", encodeURIComponent(ApiKey))
.replace("%CX%", encodeURIComponent(searchEngineID))
.replace("%Q%", encodeURIComponent(query));
var params = {
muteHttpExceptions: true
};
// Perform search
Logger.log( UrlFetchApp.getRequest(url, params) ); // Log query to be sent
var response = UrlFetchApp.fetch(url, params);
var respCode = response.getResponseCode();
if (respCode !== 200) {
throw new Error ("Error " +respCode + " " + response.getContentText());
}
else {
// Successful search, log & return results
var result = JSON.parse(response.getContentText());
Logger.log( "Obtained %s search results in %s seconds.",
result.searchInformation.formattedTotalResults,
result.searchInformation.formattedSearchTime);
return result;
}
}
例子:
[15-05-04 18:26:35:958 EDT] {
"headers": {
"X-Forwarded-For": "216.191.234.70"
},
"useIntranet": false,
"followRedirects": true,
"payload": "",
"method": "get",
"contentType": "application/x-www-form-urlencoded",
"validateHttpsCertificates": true,
"url": "https://www.googleapis.com/customsearch/v1?key=--redacted--&cx=--redacted--&q=test"
}
[15-05-04 18:26:36:812 EDT] Obtained 132,000,000 search results in 0.74 seconds.
使用 API 密钥向 Google 识别您的应用程序
(摘自Google's documentation。)
转到Google Developers Console。
-
选择一个项目,或创建一个新项目。
-
在左侧边栏中,展开 APIs & auth。接下来,点击 API。在 API 列表中,确保 Custom Search API 的状态为 ON。
。 . .
-
在左侧边栏中,选择凭据。
通过点击Public API access下的Create new Key来创建您的应用程序的API密钥。对于 Google Script 使用,请创建一个浏览器键。
创建浏览器应用程序密钥后,将API密钥复制到您的代码中。
创建自定义搜索引擎
按照说明here。创建自定义搜索引擎后,将搜索引擎 ID 复制到您的代码中。