【问题标题】:Is by.id better than by.tagname?by.id 比 by.tagname 好吗?
【发布时间】:2011-09-16 08:15:19
【问题描述】:

我正在使用 webdriver 阅读来自 gmail 的邮件,在这期间我发现了 By.id 和 By.tagname 之间的这种差异。

我正在尝试访问 id 为“:pg”的“表”。所以我可以

  1. 要么使用 By.id(":pg")
  2. 或使用 By.tagname("table") 并搜索 id 为 :pg 的元素

这是两种情况的代码。

通过.id:

WebDriver webDriver = new FirefoxDriver();
webDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
webDriver = webDriver.switchTo().frame("canvas_frame");
WebElement table1 = webDriver.findElement(By.id(":pg"));`

上面的代码,我直接得到了id为“:pg”的元素

通过.tagname:

WebDriver webDriver = new FirefoxDriver();
webDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
List<WebElement> tables = webDriver.findElements(By.tagName("table"));
for(WebElement table2: tables){
    String id = table2.getAttribute("id");
    System.out.println("id: "+ id);
    if(id != null && id.equals(":pg")){
        System.out.println("FOUND IT!!!");
    }
}

在上面的代码中,我找到所有带有 table 标记名的元素,然后查看哪个元素的 id 为 ":pg"。

这两个代码 sn-ps 本质上是相同的,但使用不同的方式(By.id 或 By.tagname)。但是,使用 By.id 的代码的第一个 sn-p 总是成功,而使用 By.tagname 的代码的第二个 sn-p 几乎总是失败。 (但它会在额外的等待下工作)

为什么 By.id 和 By.tagname 之间存在这种差异?

谢谢, 克里斯。

【问题讨论】:

    标签: testing automation automated-tests webdriver


    【解决方案1】:

    :pg 元素最初没有出现在页面上。

    使用By.Tag,selenium 不会等待:pg 元素。

    因为By.Id 示例更具体,selenium 将继续检查:pg 元素是否存在,直到隐式等待(5 秒)超时。

    By.Tag 根本不具体。在findElements(By.tagName("table") 上,Selenium 将返回页面加载后立即存在的所有表的数组。由于:pg 元素尚不存在,因此它不会出现在数组中。

    要回答您的问题,是的,最好使用By.Id,因为: 1. 更具体。 2. 节省代码行数 3. 强制 selenium 等待元素存在。

    【讨论】:

      【解决方案2】:

      根据您的问题,最好使用By.Id

      By.tag 不用于特定数据,它实际上会搜索并返回具有指定标签名称的所有表的数组。另一方面,使用 id 您可以获得用于识别/定位元素的适当输出。

      仅在未指定 id、name 或 class 时才使用标签,如果没有找到元素,最好的方法是 By.cssSelector

      谢谢

      【讨论】:

        猜你喜欢
        • 2021-11-04
        • 1970-01-01
        • 2017-05-06
        • 2019-04-29
        • 1970-01-01
        • 2021-08-20
        • 2021-05-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多