1

For the following html code in https://www.parcelhero.com/en-gb/courier-services/carriers/dhl, getattribute("style") fetches null value. Why?

<div class="dvPageShare" style="position: relative; top: -50px;"> 

Following is the Code used:

driver.get("https://www.parcelhero.com/en-gb/courier-services/carriers/dhl");
    List <WebElement>SocialLink = driver.findElements(By.tagName("div"));
        for (WebElement social : SocialLink)
 {
if( social.getAttribute("class")!=null && social.getAttribute("class").equals("dvPageShare"))
                {
System.out.println("Present");System.out.println(social.getAttribute("style"));
}

            }
user2044296
  • 504
  • 1
  • 7
  • 18

2 Answers2

1

Take the EAFP approach. Find the element by class name and handle exceptions:

try {
    WebElement social = driver.findElement(By.cssSelector("div.dvPageShare"));
    System.out.println("Present");
    System.out.println(social.getAttribute("style"));
} catch (NoSuchElementException ex) {
    System.out.println("Not Present");
}
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • According to [the docs](https://selenium.googlecode.com/git-history/master/docs/api/java/org/openqa/selenium/WebDriver.html#findElement-org.openqa.selenium.By-) `findElement should not be used to look for non-present elements, use findElements(By) and assert zero length response instead.` – JeffC Aug 26 '15 at 17:47
1

alecxe is using the right approach, I would just code it slightly differently. If there are no elements that match, code execution falls through the loop. You can specifically check for socialLinks.size() > 0, if you want... maybe log a message in that case. You'll have to decide what is best in your case.

List<WebElement> socialLinks = driver.findElements(By.cssSelector("div.dvPageShare"));
for (WebElement socialLink : socialLinks)
{
    System.out.println("Present");
    System.out.println(socialLink.getAttribute("style"));
}

This CSS Selector div.dvPageShare means find a DIV that has the class (.) dvPageShare.

I didn't try running your code but I did see that there are two DIVs with class = "dvPageShare" on that page, one of which did not have a style attribute. Maybe that's where the null is coming from?

CSS Selector reference. Learn them... they are very powerful and every automator should understand and use them.

JeffC
  • 22,180
  • 5
  • 32
  • 55
  • In order to reduce the response time I was using HtmlUnitDriver class which was working for all the classes other than "dvPageShare". It was able to identify this Class but not the "Style" attribute of this Class. Hence I was getting null.for Style. – user2044296 Aug 26 '15 at 18:41
  • hmm.. I don't have any experience using HtmlUnitDriver so I don't know what the issue might be. If you haven't already, you might try googling HtmlUnitDriver and css style... maybe others have had a similar issue with nulls. Sorry I couldn't help more. – JeffC Aug 26 '15 at 20:00