我正试图从该页的表中提取几行http://www.money.pl/pieniadze/使用xpath表达式和javascript。我可以将整个页面显示为弹出窗口,但无法使用document.eevaluate()来评估xpath表达式;已尝试使用XPathResultType,但没有结果。有人能帮忙吗?
这是我的背景页:
<html><head><script>
...
var wholePage;
setInterval(fetch, 20000);
function fetch()
{
req = new XMLHttpRequest();
var url = "http://www.money.pl/pieniadze/";
req.open("GET", url);
req.onload = process;
req.send();
}
function process()
{
wholePage = req.responseText;
}
</script></head></html>
这是弹出页面:
<html><head><script>
...
onload = setTimeout(extract, 0);
function extract()
{
chrome.browserAction.setBadgeText({text: ''});
var bg = chrome.extension.getBackgroundPage();
var EurPlnPath = "//tr[@id='tabr_eurpln']";
var tempDiv = document.getElementById('current');
tempDiv.innerHTML = bg.wholePage;
var oneTopic = document.evaluate( EurPlnPath, bg.wholePage, null, XPathResult.ANY_TYPE, null)
var res = oneTopic.iterateNext();
}
</script></head>
<body>
<div id="current">
</div>
</body>
</html>
不能在纯字符串上使用XPath。您必须先将字符串转换为文档。例如,使用DOMParser
。目前的浏览器还不支持text/html
。为了让它发挥作用,你必须包括这个答案中指定的代码:
var bgWholePage = new DOMParser().parseFromString(bg.wholePage, 'text/html');
document.evaluate( EurPlnPath, bgWholePage, ...
如果要在后台页面解析文档,请使用bg.document.evaluate
而不是document.evaluate
:
var oneTopic = bg.document.evaluate( EurPlnPath, bg.wholePage, null, XPathResult.ANY_TYPE, null)
尝试document.querySelector("tr#tabr_eurpln")
而不是document.evaluate,这将返回一个与选择器相对应的DOM元素。