I was working on reading mails from gmail using webdriver and in between I hit upon this difference between By.id and By.tagname.
I am trying to get access to a “table” whose id is “:pg”. So I could
- Either use By.id(“:pg”)
- OR use By.tagname(“table”) and search for an element with id :pg
Here is the code for both cases.
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"));`
Above code, I directly get the element which has 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!!!");
}
}
Above code, I find all elements with the tagname of table and then see which one has the id “:pg”.
Both these code snippets are essentially doing the same but using different ways(By.id or By.tagname). However, the first snippet of code which uses By.id always succeeds while the second snippet of code which uses By.tagname fails almost always. (It will work with additional waiting however)
Why is this difference between By.id and By.tagname?
Thanks,
Chris.
The
:pgelement is not present on the page initially.Using
By.Tag, selenium will not wait for the:pgelement.Because
By.Idexample is more specific, selenium will continue checking if the:pgelement exists until the implicit wait (5 seconds) times out.By.Tag is not specific at all. On
findElements(By.tagName("table"), Selenium will return an array of all the tables that are present immediately after the page loads. As the:pgelement is not present yet, it will not be in the array.To answer your question, yes it is better to use
By.Idbecause:1. It is more specific.
2. Saves lines of code
3. Forces selenium to wait for the element to exist.