Getting the Values of All the CSS Properties of a Selected Element in Selenium

Getting the values of all the CSS properties of a selected element in Selenium

Unfortunately

this is not possible with native Selenium API.

But using Javascript you can:

You can use some javascript support, using Seleniums' JavascriptExecutor.executeScript functionality.

The necessary js code can be found here and here(as proposed by @Mahsum Akbas)

Now here is the Java/Selenium Code that will return you a string in the form of "css-attribute01:value01; css-attribute02:value02;".

Be aware that this will return ALL css-attributes on the element.

WebElement we = driver.findElement(By.tagName("div"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
String script = "var s = '';" +
"var o = getComputedStyle(arguments[0]);" +
"for(var i = 0; i < o.length; i++){" +
"s+=o[i] + ':' + o.getPropertyValue(o[i])+';';}" +
"return s;";

System.out.println(executor.executeScript(script, we));

You can change the script according to your needs. For example you could return a string that ONLY has all the values without the attributes. Feel free to change and experiment.

Update

If you would be interested in only the inline-styles of the element, then you can use "native" Selenium as pointed out by @JeffC in the comments:

driver.findElement(By.tagName("div")).getAttribute("style")

BUT!:

This will give you only the "inline styles" and NOT all the css-styles that are applied to an element. If you run both versions after one another and print the results you will see the immense difference.

How to get all css-styles from a dom-element using Selenium, C#

you can use getCSSValue method of IWebElement. For example to get the background color of a element you can try the following code.

var chromeOptions = new ChromeOptions();
chromeOptions.AddArguments("headless");

var browser = new ChromeDriver(chromeOptions);

var url = "https://example.com";
browser.Navigate().GoToUrl(url);

var domElement = browser.FindElement(By.TagName("html"));
var color = domElement.GetCssValue("background-color");

May you can try the following javascript code using selenium C#;

string properties = ((IJavaScriptExecutor)driver).ExecuteScript("return window.getComputedStyle(arguments[0],null).cssText", domElement);
strArr = properties.split(";")

for (count = 0; count <= strArr.Length - 1; count++)
{
console.log(strArr[count]);
}

Selenium WebDriver - getCssValue() method

Yes, all correct.

Here's a screenshot of where to find font-size through Firebug.

Sample Image

Since the ids are supposed to be unique (at least for this page), you don't need findElements to find a list of elements with id by-id and loop through, instead, you use findElement to get the element directly.

try{
WebElement byId = driver.findElement(By.id("by-id"));

System.out.println(byId.getTagName());

System.out.println("get the text for web element with id='by-id' ");
System.out.println("------------------------------------------------------------");
System.out.println(byId.getText());
System.out.println("------------------------------------------------------------");
System.out.println(byId.getAttribute("id"));
System.out.println(byId.getCssValue("font-size"));
}
}

How to get values of same class/properties in Selenium C#?

You need a XPath expression to catch all the a elements at once and store them in a list.

When there are no other anchor tags then the Endorsements:

IList<IWebElement> listOfEndorsements= Driver.FindElements(By.XPath("//a"));

When there are other kind of anchor tags you can try:

IList<IWebElement> listOfEndorsements= Driver.FindElements(By.XPath("//div[contains(@ng-repeat,'prop.Endorsements')]/a"));

Then you can use a ForEach loop to extract from the list of IWebElements the information you need.Like:

foreach (var endorsement in listOfEndorsements)
{
var text = endorsement.Text;
}

Get a css property with selenium webdriver by selectors

Perhaps a little bit of a longer route but you could try getting a list of all the elements and checking the css-properties, with the appropriate method.

List<Webelement> elements = driver.findElements(By.cssSelector(".item-result .content-main .block-opening"));
for (Webelement element : elements) {
if (element.getCssValue("text-indent").equals("-999em")) {
return element;
}
}

Caveat, I've never tried to get the text-indent value, as such I can't guarantee that the above will work.

http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/WebElement.html#getCssValue(java.lang.String)

How to get child property value of a element property using selenium webdriver, NUnit and C#

Seems you were pretty close. To retrieve the cssText and fontWeight you can use the getComputedStyle() and then use getPropertyValue() to retrieve the style and you can use the following solution:

IJavascriptExecutor jse = (IJavascriptExecutor)driver;
String cssText_script = "var x = getComputedStyle(arguments[0]);" +
"window.document.defaultView.getComputedStyle(x,null).getPropertyValue('cssText');"; ";
String fontWeight_script = "var x = getComputedStyle(arguments[0]);" +
"window.document.defaultView.getComputedStyle(x,null).getPropertyValue('fontWeight');"; ";
string myCssText = (string) jse.ExecuteScript(cssText_script, Element3);
string myFontWeight = (string) jse.ExecuteScript(fontWeight_script, Element4);

Note: You need to induce WebDriverWait along with the ExpectedConditions as ElementIsVisible method.

Getting specific elements in selenium

Seems you were pretty close enough.

[<selenium.webdriver.remote.webelement.WebElement (session="1c044455cf883fdedf6845bcd456bfab", element="0.23338884730774767-2")>]

represents the element where as you were looking for the text within the element.

To extract the texts e.g. N06D-X, N07X, etc from all of the <p> tags using Selenium and python you have to induce WebDriverWait for visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

  • Using CSS_SELECTOR and get_attribute("innerHTML"):

    print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "li.data-list__property#who-atc-codes span.data-list__property-value p")))])
  • Using XPATH and text attribute:

    print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//li[@class='data-list__property' and @id='who-atc-codes']//span[@class='data-list__property-value']//p")))])
  • Note : You have to add the following imports :

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC


Outro

Link to useful documentation:

  • get_attribute() method Gets the given attribute or property of the element.
  • text attribute returns The text of the element.
  • Difference between text and innerHTML using Selenium


Related Topics



Leave a reply



Submit