我正在尝试从 Zacks.com 网站参数中的 URL 获取类“rank_view”的值。 这是我做的脚本:
function ZacksRank (url) {
//url.toString().trim();
// Get the content of that site as a string
var d = UrlFetchApp.fetch(url).getContentText();
// String to search (in your case following the class value)
// Note that the string to be search contains 19 characters
var search = 'class="rank_view">';
// Get the index where the data we are interested is found in the string
var index = d.search(search);
// Get the character at that index (plus 19 is because search returns the
// index of the first character of the search, in this case it would return
// the index of c (of class) and therefore we must add to the index the length
// of our string
var value = d.charAt(index+search.length);
return(value);
}
我这样称呼这个函数:
=zacksrank("http://www.zacks.com/stock/quote/abbv")
但我收到以下错误消息:
Exception: Address unavailable: http://www.zacks.com/stock/quote/abbv
有人可以帮忙吗? 十分感谢 :) 加布里埃尔
此错误意味着您尝试获取的页面当前不可用。你的脚本没有任何问题。 “zacks.com”网站根本没有响应。
为了证明这一点,您可以使用您确定可以使用的网页的 URL,例如“https://www.google.com”。
就我而言,问题是因为它所创建的网站或框架具有一种限制请求的机器人程序。
要解决此问题,请尝试将代理包含在标头中:
第 1 步:从浏览器创建请求并访问网络窗口上的第一个请求:
第 2 步:找到用户代理和其他关键字段:
请求标头 > 用户代理:(可能是最后一个字段)
第3步:这是我的请求示例:
var options = {
headers: {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/254.354 (KHTML, like Gecko) Chrome/100.0.0.0 Safari/254.254',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9saf,image/,image/webp,image/apng,*/*;q=0.ds,application/signed-exchange;v=bas;q=0.7',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.9,pt-BR;q=0.8,pt;q=0.7',
'Upgrade-Insecure-Requests': '1',
},
};
var response = UrlFetchApp.fetch(url, options);
return response.getContentText()
额外:Google 脚本允许您在循环内使用诸如 setTimeOut 之类的东西:
使用它来防止请求限制:
function teste () {
let content = await getContentGs(url);
let siteIsRunning = false
while (!siteIsRunning) {
if (content != 'try again') {
siteIsRunning = true
} else {
content = await getContentGs(url);
}
}
return content
}
async function getContentGs(url) {
var options = {YOUR OPTIONS HERE};
try {
var response = UrlFetchApp.fetch(url, options);
return response.getContentText()
} catch (error) {
console.log('try again', error.message)
Utilities.sleep(2 * 1000) // <-------------- USE THIS
return 'try again'
}
}
上面的代码我测试了好几次,没有错误。
然而,直接获取 www.zacks.com 数据通常效率似乎很低。
我的建议是使用 https://quote-feed.zacks.com/index.php?t=ABBV 端点。下面是代码:
function ZacksRank(ticker) {
const URL = 'https://quote-feed.zacks.com/index.php?t=' + ticker;
var response = UrlFetchApp.fetch(URL);
if (response.getResponseCode() != 200) return 'Unavailable';
var j = JSON.parse(response.getContentText());
Logger.log(JSON.stringify(j, null, 2)); // More info, if required
return j[ticker].zacks_rank; // Zacks rank value
}
特别是对于 ABBV 股票代码,可以通过以下方式使用:
=ZacksRank("ABBV")
如果查看记录器输出,您可能希望从同一端点获取更多股票信息。变量
j
已包含它。