步骤:
代码试用:
package com.practice;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Buttons {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Oderint dum metuant\\eclipse-workspace\\JAR FILES\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.toolsqa.com/automation-practice-switch-windows/");
List <WebElement> buttons = driver.findElements(By.tagName("button"));
for ( int i=0; i<buttons.size();i++){
WebElement button = buttons.get(i);
if(button.isEnabled()){
System.out.println(buttons);
}}}}
答案 0 :(得分:1)
要打印url中的所有按钮文本,可以使用 Java8的 stream()
和map()
,还可以使用以下解决方案:
代码行:
System.out.println(driver.findElements(By.tagName("button")).stream().map(element->element.getAttribute("innerHTML")).collect(Collectors.toList()));
控制台输出:
[New Browser Window, New Message Window, New Browser Tab, Alert Box, Timing Alert, Change Color, Change Color, Disabled, Visible, , , , , , ]
答案 1 :(得分:0)
我使用了 By.cssSelector 方法
,而不是使用 By.tagName 方法。这是工作代码...
package stackOverflow;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class ToolsqaCom {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "D:\\Tushar\\JARs\\selenium\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.toolsqa.com/automation-practice-switch-windows");
driver.manage().window().maximize();
// ArrayList<String> l1 = new ArrayList<String>();
// WebElement b1 = driver.findElement(By.id("button1"));
// l1.add(b1.getText());
java.util.List<WebElement> b2 = driver.findElements(By.cssSelector("p button"));
for (int i = 0; i < b2.size() - 1; i++) {
String string = b2.get(i).getText();
System.out.println(string);
}}}
以下是输出:
新浏览器窗口
新消息窗口
“新浏览器”标签
警报框
定时提醒
更改颜色
更改颜色
已禁用
答案 2 :(得分:0)
回答。如果条件块被删除,则更改打印语句。请参阅下面的代码:
List <WebElement> buttons = driver.findElements(By.tagName("button"));
for ( int i=0; i<buttons.size();i++)
{
WebElement button = buttons.get(i);
System.out.println(button.getText());//It prints all the buttons name displayed on the page
}
A。保留if条件块,只需更改print语句。请参考以下代码:
List <WebElement> buttons = driver.findElements(By.tagName("button"));
for ( int i=0; i<buttons.size();i++)
{
WebElement button = buttons.get(i);
//System.out.println(button.getText()); //It prints all the buttons name displayed on the page
if(button.isEnabled())
{
System.out.println(button.getText()); //It prints all the buttons name which are enabled on the page
}
}