Get css value by CSS and use in Selenium

2019-06-03 03:02发布

问题:

I try to get some website attribute (colour of the cell) and compare in Selenium.

When I put this:

javascript:window.getComputedStyle(document.getElementById("simple_cname"),null).getPropertyValue("background-color");

in Chrome Omnibox, I receive correct answer, but when I, by using storeEval or assertEval try to get this value it does not work correctly.
edit: I put to selenium command like this. I use storeEval and when I echo the value it returns me this command. I use Firefox. I used Chrome just to chech if the command is correct. (it should be "rgb(220, 22, 92)" ) edit2: Yes, the command is ok, but I have a problem with using it in Selenium-IDE tool. It do not returns the value when I use it with storeEval command. log: [info] script is: var test javascript:window.getComputedStyle(document.getElementById("simple_cname"),null).getPropertyValue("background-color"); echo test; [info] Executing: |echo | ${test} | | [info] echo: var test javascript:window.getComputedStyle(document.getElementById("simple_cname"),null).getPropertyValue("background-color"); echo test;


I put to selenium command like this. I use storeEval and when I echo the value it returns me this command. I use Firefox. I used Chrome just to chech if the command is correct. (it should be "rgb(220, 22, 92)" )

回答1:

You need to remove the javascript: part and refer to document as window.document. The command will then look like this:

window.getComputedStyle(window.document.getElementById('simple_cname'),null).getPropertyValue('background-color');

The javascript: part is only needed when running the code from your URL bar, it's redundant anywhere else. Use the Console instead of your Omnibox to run JS commands in Chrome.

The document -> window.document thing is mentioned in the docs under the storeEval section.

Also, note that your script will only work in modern browsers, it will fail in IE < 9. If you're okay with it, fine. If not, Google has the solution.