Chr*_*ney 2 testing automation automated-tests webdriver
我正在使用webdriver从gmail阅读邮件,在此之间,我在By.id和By.tagname之间找到了这个区别.
我试图访问一个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"));`
Run Code Online (Sandbox Code Playgroud)
上面的代码,我直接得到id为":pg"的元素
By.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!!!");
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的代码中,我找到了所有带有tablename标签名的元素,然后查看哪个元素的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"),Onlenium将返回页面加载后立即出现的所有表的数组.由于:pg元素尚未存在,它将不在数组中.
要回答你的问题,是的,最好使用,By.Id因为:1.它更具体.2.保存代码行3.强制selenium等待元素存在.