【问题标题】:"Style" attribute not getting identified in Selenium Webdriver for the mentioned case对于上述案例,在 Selenium Webdriver 中未识别“样式”属性
【发布时间】:2015-08-26 13:14:50
【问题描述】:

对于https://www.parcelhero.com/en-gb/courier-services/carriers/dhl 中的以下html 代码,getattribute("style") 获取空值。为什么?

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

以下是使用的代码:

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"));
}

            }

【问题讨论】:

    标签: selenium styles webdriver getattribute


    【解决方案1】:

    采用EAFP 方法。 通过类名查找元素并处理异常:

    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");
    }
    

    【讨论】:

    • 根据the docsfindElement should not be used to look for non-present elements, use findElements(By) and assert zero length response instead.
    【解决方案2】:

    alecxe 使用了正确的方法,我只是将其编码略有不同。如果没有匹配的元素,则代码执行将通过循环。您可以专门检查socialLinks.size() &gt; 0,如果您愿意...也许在这种情况下记录一条消息。您必须决定最适合您的情况。

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

    此 CSS 选择器 div.dvPageShare 表示查找具有类 (.) dvPageShare 的 DIV

    我没有尝试运行您的代码,但我确实看到该页面上有两个DIVs 和class = "dvPageShare",其中一个没有样式属性。也许这就是null 的来源?

    CSS Selector reference。学习它们...它们非常强大,每个自动化者都应该了解和使用它们。

    【讨论】:

    • 为了减少响应时间,我使用了 HtmlUnitDriver 类,它适用于“dvPageShare”以外的所有类。它能够识别这个类,但不能识别这个类的“样式”属性。因此我得到了 null.for Style。
    • hmm.. 我没有任何使用 HtmlUnitDriver 的经验,所以我不知道问题可能是什么。如果您还没有,您可以尝试使用谷歌搜索 HtmlUnitDriver 和 css 样式......也许其他人也遇到过类似的空值问题。抱歉,我帮不上忙。
    猜你喜欢
    • 1970-01-01
    • 2017-05-05
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多