简体   繁体   English

硒cssSelector与tagName

[英]selenium cssSelector vs. tagName

I have a use case that I need to find all iframe and object tags from the page. 我有一个用例,需要从页面中查找所有iframe和对象标签。

Currently I'm using cssSelector() method. 目前,我正在使用cssSelector()方法。 I have noticed that there is also tagName() method. 我注意到,还有tagName()方法。

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> . findElement(By.tagName("a_tag"))将通过html标签(例如<iframe><div> findElement(By.tagName("a_tag"))查找元素。 But you can only provide it with html tags, not css classes, etc ... 但是您只能为它提供html标签,而不是css类等。

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")) 使用findElement(By.cssSelector("a_tag"))您可以找到带有html标签的元素,但也可以提供一个CSS类,例如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 然后执行for循环进行测试

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. 建议使用cssSelector / id / xpath / etc ...,因为如果最初页面上不存在该元素,它将等待显示“所需元素”。

Because By.cssSelector is more specific, selenium will continue checking if the element exists until the implicit wait (x seconds) times out. 因为By.cssSelector更具体,所以selenium将继续检查元素是否存在,直到隐式等待(x秒)超时为止。

By.Tag is not specific at all. By.Tag根本不是特定的。 Using By.tagName, selenium will not wait for the element. 使用By.tagName,硒将不等待该元素。 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. 在findElements(By.tagName(“ table”)上,Selenium将返回页面加载后立即存在的所有表的数组。由于尚不存在“需要”元素,因此它将不在数组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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