您要查找的数据的格式并不适合自动提取,但我们可以使用它。这个答案中的getElementByVal()
函数可以重构为 create ,它将返回一个包含所有匹配文档元素的数组,让我们可以做进一步的搜索。getElementsByVal()
/**
* Traverse the given XmlElement, and return an array of matches.
* Note: 'class' is stripped during parsing and cannot be used for
* searching, I don't know why.
* <pre>
* Example: getElementsByVal( body, 'input', 'value', 'Go' ); will find
*
* <input type="submit" name="btn" value="Go" id="btn" class="submit buttonGradient" />
* </pre>
*
* @param {XmlElement} element XML document element to start search at.
* @param {String} id HTML <div> id to find.
*
* @return {[XmlElements]} All matching elements (in doc order).
*/
function getElementsByVal( element, elementType, attr, val ) {
var results = [];
// If the current element matches, remember it.
if (element[attr]
&& element[attr] == val
&& element.getName().getLocalName() == elementType) {
results.push( element );
}
// Check element's children
var elList = element.getElements();
var i = elList.length;
while (i--) {
// (Recursive) Check each child, in document order.
results = results.concat(getElementsByVal( elList[i], elementType, attr, val ));
}
// Return summary of matches
return results;
}
为了利用这个新的辅助函数,如果我们创建一个函数getIndicators()
,它接受一个包含我们感兴趣的时间点的字符串参数——Mon. Jul 29, 2013 07:40:00
例如?匹配的文本将在 get 的area
元素中找到shape="rect"
,我们将在名为 的属性中找到它onmousemove
。这是我们的功能:
function getIndicators(timeString) {
var txt = UrlFetchApp.fetch("http://www.barchart.com/chart.php?sym=DXU13&t=BAR&size=M&v=2&g=1&p=I:5&d=L&qb=1&style=technical&template=").getContentText();
var doc = Xml.parse(txt,true);
var body = doc.html.body;
var indicators = "not found";
// Look for elements matching: < area shape="rect" ... >
var chartPoints = getElementsByVal(body, 'area', 'shape', 'rect');
// Search for the chartPoint with tooltip containing the time we care about
for (var i=0; i<chartPoints.length; i++) {
if (chartPoints[i].onmousemove.indexOf(timeString) > -1) {
// found our match
indicators = chartPoints[i].onmousemove;
}
}
return indicators
}
就目前而言,它将返回分配给的整个文本值onmousemove
;智能的解析练习留给你。
这是一个可以提供帮助的测试功能:
function test_getIndicators() {
Logger.log( getIndicators("Mon. Jul 29, 2013 07:40:00" ) );
}
运行时,这是日志(今天,无论如何......):
[13-07-29 16:47:47:266 EDT] showOHLCTooltip(event, 'B', '[Mon. Jul 29, 2013 07:40:00]', 'DXU13', '81.8050000', '81.8300000', '81.8000000', '81.8200000')