如何通过 Java 使用 Selenium 打印 url 中的所有按钮文本按钮、文本、Java、Selenium

2023-09-07 01:15:08 作者:独坐山巅

步骤:

转到网站 > https://www.toolsqa.com/automation-practice-switch-windows/从该页面获取按钮列表打印页面上显示的按钮的名称.

代码试用:

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);
                }}}}         

推荐答案

我没有使用 By.tagName 方法,而是使用了 By.cssSelector 方法

Instead of using By.tagName method I used By.cssSelector method

这是工作代码...

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);

    }}}

以下是输出:

新的浏览器窗口

新消息窗口

新的浏览器标签

警报框

定时提醒

改变颜色

改变颜色

已禁用

 
精彩推荐
图片推荐