我正在使用 webdriver 阅读来自 gmail 的邮件,在此期间我偶然发现了 By.id 和 By.tagname 之间的区别。
我正在尝试访问 ID 为“:pg”的“表”。所以我可以
- 要么使用 By.id(":pg")
- 或使用 By.tagname("table") 并搜索 id 为 :pg 的元素
这是两种情况的代码。
By.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”。
这两个代码片段本质上都在做同样的事情,但使用不同的方式(By.id 或 By.tagname)。但是,使用 By.id 的第一段代码总是成功,而使用 By.tagname 的第二段代码几乎总是失败。 (不过,它会在额外等待的情况下工作)
为什么 By.id 和 By.tagname 之间存在这种差异?
谢谢, 克里斯。
最佳答案
:pg
元素最初不出现在页面上。
使用 By.Tag
,selenium 不会等待 :pg
元素。
因为 By.Id
示例更具体,selenium 将继续检查 :pg
元素是否存在,直到隐式等待(5 秒)超时。
By.Tag 一点也不具体。在 findElements(By.tagName("table")
上,Selenium 将返回页面加载后立即出现的所有表的数组。因为 :pg
元素是还不存在,它不会在数组中。
要回答您的问题,是的,最好使用 By.Id
因为:
1.更具体。
2. 节省代码行
3.强制selenium等待元素存在。
关于testing - by.id 比 by.tagname 好吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6371865/