简体   繁体   中英

selenium cssSelector vs. tagName

I have a use case that I need to find all iframe and object tags from the page.

Currently I'm using cssSelector() method. I have noticed that there is also tagName() method.

What is the difference between these 2 methods with the above use case ?

findElement(By.tagName("a_tag")) will find elements by html tags such as <iframe> , <div> . But you can only provide it with html tags, not css classes, etc ...

With findElement(By.cssSelector("a_tag")) you can find elements with html tags but you can also give a css class for example findElement(By.cssSelector("div.myClass"))

For your case you can use :

List<WebElement> iframes = driver.findElements(By.tagName("iframe"))
List<WebElement> objects = driver.findElements(By.tagName("object"))

And then perform a for loop to do your tests

It's recommended to use cssSelector/id/xpath/etc ... By since it will wait for the "needed element" displayed if the element is not present on the page initially.

Because By.cssSelector is more specific, selenium will continue checking if the element exists until the implicit wait (x seconds) times out.

By.Tag is not specific at all. Using By.tagName, selenium will not wait for the element. On findElements(By.tagName("table"), Selenium will return an array of all the tables that are present immediately after the page loads. As the "needed" element is not present yet, it will not be in the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM