2

I'm trying to extract a few rows from the table from this page http://www.money.pl/pieniadze/ using xpath expression and javascript. I can get the whole page being displayed as a pop-up but I cannot evalute xpath expression with document.evaluate(); Have tried to play with XPathResultType but no results. 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>
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
matcheek
  • 4,887
  • 9
  • 42
  • 73

2 Answers2

3

You can't use XPath on plain strings. You have to convert the string into a document first. For example, using the DOMParser. Current browsers do not support text/html yet. 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:

var oneTopic = bg.document.evaluate( EurPlnPath, bg.wholePage, null, XPathResult.ANY_TYPE, null)
Community
  • 1
  • 1
Rob W
  • 341,306
  • 83
  • 791
  • 678
2

Try document.querySelector("tr#tabr_eurpln") instead of document.evaluate, this will return a DOM element, corresponding to selector.

Just_Mad
  • 4,029
  • 3
  • 22
  • 30
  • Don't use `querySelectorAll`, but `querySelector`. IDs have to be unique, so you can be sure that the selection returns only one element. `querySelector` is much [faster](http://jsperf.com/getelementbyid-vs-queryselector/5) than XPath, so this answer contains a good advice. Still, this method cannot work with plain strings, see my answer for that part. – Rob W Feb 25 '12 at 18:46
  • Rob is right, if these few rows have a property, that can definetly select them, you'd better use querySelectorAll with such properties. then you will get a list of such elements at once. – Just_Mad Feb 25 '12 at 18:56