Testing by.id比by.tagname好吗?
我当时正在使用webdriver从gmail读取邮件,其间我发现了By.id和By.tagname之间的差异 我试图访问一个id为:pg的“表”。所以我可以Testing by.id比by.tagname好吗?,testing,automation,automated-tests,webdriver,Testing,Automation,Automated Tests,Webdriver,我当时正在使用webdriver从gmail读取邮件,其间我发现了By.id和By.tagname之间的差异 我试图访问一个id为:pg的“表”。所以我可以 由.id使用(“:pg”) 或按.tagname(“表”)使用并搜索id为pg的元素 下面是这两种情况的代码 By.id: WebDriver webDriver = new FirefoxDriver(); webDriver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
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”的元素
按标记名:
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!!!");
}
}
WebDriver-WebDriver=newfirefoxdriver();
webDriver.manage().timeouts().implicitlyWait(5,TimeUnit.SECONDS);
列表表=webDriver.findElements(按.tagName(“表”));
for(WebElement表2:表){
字符串id=table2.getAttribute(“id”);
System.out.println(“id:+id”);
如果(id!=null&&id.equals(“:pg”)){
System.out.println(“找到了!!!”;
}
}
在上面的代码中,我找到了所有带有table标记名的元素,然后查看哪个元素的id为“:pg”
这两个代码段基本上做的相同,但使用的方式不同(按.id或按.tagname)。但是,使用By.id的第一段代码总是成功的,而使用By.tagname的第二段代码几乎总是失败的。(但需要额外等待)
为什么By.id和By.tagname之间存在这种差异
谢谢,
Chris.页面上最初不存在
:pg
元素
使用By.Tag
,selenium不会等待:pg
元素
由于By.Id
示例更具体,selenium将继续检查:pg
元素是否存在,直到隐式等待(5秒)超时
标记一点也不具体。在findElements(By.tagName(“table”)
上,Selenium将返回页面加载后立即出现的所有表的数组。由于:pg
元素尚未出现,它将不在数组中
要回答您的问题,最好使用.IdBy
,因为:
1.更具体。
2.保存代码行
3.强制selenium等待元素存在。根据您的问题,最好使用By.Id By.tag不用于特定数据,它实际上将搜索并返回具有指定标记名的所有表的数组。另一方面,使用id可以获得用于标识/定位元素的适当输出 仅当未指定id、名称或类时才选择标记,如果未找到元素,则最好的方法是使用.cssSelector 谢谢