我正在尝试创建一个使用Google应用程序的自动化过程--从这样的页面中抓取价格数据的脚本:
https://www.barchart.com/stocks/quotes/$AVVN/price-history/historical
具有挑战性的是,网页上的数据是“懒惰加载”的,所以我在其他网页上使用的“传统”替罪羊方法在这里不起作用。
我曾考虑过其他解决这个问题的方法,但:
在下面的帖子中,我发现了一个类似的问题--从omegastripe那里得到了一个非常详细和翔实的答复:Open webpage, select all, copy into sheet
当我运行代码时,-but:
function test(){
var url = 'https://www.barchart.com/proxies/core-api/v1/historical/get?symbol=%24AVVN&fields=tradeTime.format(m%2Fd%2Fy)%2CopenPrice%2ChighPrice%2ClowPrice%2ClastPrice%2CpriceChange%2Cvolume%2CsymbolCode%2CsymbolType&startDate=2019-04-15&endDate=2019-07-15&type=eod&orderBy=tradeTime&orderDir=desc&limit=2000&meta=field.shortName%2Cfield.type%2Cfield.description&raw=1';
var options = {
"muteHttpExceptions": false
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
}-then我得到以下错误:
Request failed for https://www.barchart.com/proxies/core-api/v1/historical/get?symbol=%24AVVN&fields=tradeTime.format(m%2Fd%2Fy)%2CopenPrice%2ChighPrice%2ClowPrice%2ClastPrice%2CpriceChange%2Cvolume%2CsymbolCode%2CsymbolType&startDate=2019-04-15&endDate=2019-07-15&type=eod&orderBy=tradeTime&orderDir=desc&limit=2000&meta=field.shortName%2Cfield.type%2Cfield.description&raw=1 returned code 500. Truncated server response: <!doctype html> <html itemscope itemtype="http://schema.org/WebPage" lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="wi... (use muteHttpExceptions option to examine full response) (line 57, file "DS#1")基本上是“哎呀,出了点问题。我们很抱歉.这一页似乎有问题。”如果您将地址粘贴到浏览器中。
,所以我的问题是:如何从这个页面中抓取数据,或者条形图现在已经成功地阻止了这个刮取选项?
发布于 2019-07-16 16:00:32
我发现获取数据的唯一方法是使用解决方法,从控制台获取要获取的请求URL,但另外,在使用fetch()方法1时,必须将“xsrf token”和“cookie”头添加到选项中。
您也可以从控制台获得“xsrf token”和“cookie”请求头。唯一的问题是cookie和xsrf令牌在2小时内是有效的,这是因为它们实现了跨站点请求伪造保护2。

下面是我测试和使用的代码:
function testFunction() {
var url = 'https://www.barchart.com/proxies/core-api/v1/historical/get?symbol=%24AVVN&fields=tradeTime.format(m%2Fd%2Fy)%2CopenPrice%2ChighPrice%2ClowPrice%2ClastPrice%2CpriceChange%2Cvolume%2CsymbolCode%2CsymbolType&startDate=2019-04-16&endDate=2019-07-16&type=eod&orderBy=tradeTime&orderDir=desc&limit=2000&meta=field.shortName%2Cfield.type%2Cfield.description&raw=1';
var map = {
"x-xsrf-token": "XXXXX",
"cookie": "XXXXX"
}
var options = {
"method": "get",
"muteHttpExceptions": false,
"headers": map
};
var response = UrlFetchApp.fetch(url, options);
Logger.log(response);
var json = JSON.parse(response);
Logger.log(json.data[0]);
}发布于 2019-07-17 06:44:14
您不能使用Google脚本来延迟加载网页,因为它们只返回网页的HTML内容,并且在返回内容之前不等待JavaScript加载。
一个可能的解决方案是使用Google函数来加载页面。云函数提供了一个HTTP,可以通过URLFetch服务从Apps脚本直接调用该API。
https://stackoverflow.com/questions/57054074
复制相似问题