简体   繁体   English

在Chrome中评估xpath表达式

[英]Evaluating xpath expression in Chrome

I'm trying to extract a few rows from the table from this page http://www.money.pl/pieniadze/ using xpath expression and javascript. 我正在尝试使用xpath表达式和javascript从本页http://www.money.pl/pieniadze/中的表中提取几行。 I can get the whole page being displayed as a pop-up but I cannot evalute xpath expression with document.evaluate(); 我可以将整个页面显示为弹出窗口,但无法使用document.evaluate()评估xpath表达式。 Have tried to play with XPathResultType but no results. 尝试使用XPathResultType,但没有结果。 Can anybody help? 有人可以帮忙吗?

Here is my background page: 这是我的背景页面:

<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>

and here is the popup page: 这是弹出页面:

<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>

You can't use XPath on plain strings. 您不能在纯字符串上使用XPath。 You have to convert the string into a document first. 您必须先将字符串转换为文档。 For example, using the DOMParser . 例如,使用DOMParser Current browsers do not support text/html yet. 当前的浏览器尚不支持text/html To get this to work, you have to include the code as specified at this answer : 要使其正常工作,您必须包含此答案中指定的代码:

var bgWholePage = new DOMParser().parseFromString(bg.wholePage, 'text/html');
document.evaluate( EurPlnPath, bgWholePage, ...

If you want to parse the document at the background page, use bg.document.evaluate instead of document.evaluate : 如果要在后台页面解析文档,请使用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元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM