我试着教自己一些编码和从网站上抓取。但我在添加参数方面有问题。没有参数,我需要调整函数,这是不可取的。这是没有参数的工作函数。
function import1() {
var html, content = '';
var response = UrlFetchApp.fetch("https://www.fundsquare.net/security/summary?idInstr=275136");
if (response) {
html = response.getContentText();
if (html) content = html.match(/<span class="surligneorange">([\d.]*).*<\/span>/)[1];
}
return content;
}我就是这样调整它的,所以它有参数:
function importval(url, name) {
var found, html, content = '';
var response = UrlFetchApp.fetch(url);
found = "/<span class="+name+">([\d.]*).*<\/span>/"
if (response) {
html = response.getContentText();
if (html) content = html.match(found)[1];
}
return content;
}但是,它不起作用。当我试图调整它时,它会产生不同的错误。问题在于URL有一些错误,而name与其他错误有关。使用上面的代码,错误是url变量没有值。我不知道如何用参数来制作公式。
我知道代码found = "/<span class="+name+">([\d.]*).*<\/span>/"不会对每个网站都起作用,但是如果我能做到这一点,我可以想办法调整它,这样它就能适用于我想要的网站。现在它只适用于span类,但这可以更改,这样它就可以用于更多的网站(我认为)。
编辑6-6 16:05这是一个关于解决方案的问题
这是匹配方应该找到的代码:(/<span class="surligneorange">([\d.]*).*<\/span>/)[1];
这是代码,你写的("<span class=\""+name+"\">([\\d.]*).*<\\/span>")。
为什么需要两个\中的\""+name+"\"?在使用它时,显示哪个部分是字符串,哪个部分是应该实现的变量似乎很重要。但我不确定它是如何工作的,因为"<span class=\"包括\,但"+name+"\"在这里,它似乎介于" "之间。为什么包括一个\,而在" "之间单独包含一个
发布于 2020-06-06 09:14:14
这个修改怎么样?
修改要点:
RegExp。html.match(found)就变成了null。在这种情况下,您的脚本会发生错误。所以我修改了这个。当您的脚本被修改时,如下所示。
修改脚本:
function importval(url, name) {
var found, html, content = '';
var response = UrlFetchApp.fetch(url);
found = new RegExp("<span class=\""+name+"\">([\\d.]*).*<\\/span>"); // <--- Modified
if (response) {
html = response.getContentText();
if (html) {
content = html.match(found); // <--- Modified
if (content && content.length == 2) { // <--- Added
content = content[1];
}
}
}
return content;
}name为surligneorange时,正则表达式变为/<span class="surligneorange">([\d.]*).*<\/span>/。url和name分别为https://www.fundsquare.net/security/summary?idInstr=275136和surligneorange时,将检索31.15。null。注意:
参考资料:
添加:
关于你的补充问题,我想回答如下。
在这种情况下,作为理解它的一种简单方法,检查found的值如何?在现阶段,我们已经发现/<span class="surligneorange">([\d.]*).*<\/span>/是正确的值。
当name是surligneorange时,
found of found = new RegExp("<span class="+name+">([\d.]*).*<\/span>");如下。- `/<span class=surligneorange>([d.]*).*<\/span>/`
found of found = new RegExp("<span class=\""+name+"\">([\\d.]*).*<\\/span>");如下。- `/<span class="surligneorange">([\d.]*).*<\/span>/`
- This is the same with the correct value.
在这种情况下,<\/span>和<\\/span>是相同的结果。
在本文件中,可以看到When using the constructor function, the normal string escape rules (preceding special characters with \ when included in a string) are necessary.。
https://stackoverflow.com/questions/62229461
复制相似问题