【问题标题】:How to pass a variable string within the xpath to identify an element in Selenium and Java如何在 xpath 中传递变量字符串以识别 Selenium 和 Java 中的元素
【发布时间】:2020-07-27 04:22:41
【问题描述】:

如何在 xpath 中传递变量字符串来识别 Selenium 和 Java 中的元素?

代码试验:

System.out.println("Name:\n");
String name = sc.nextLine();
System.out.println("Enter the no. of messages:\n");
int count = sc.nextInt();
System.out.println("Enter what you want to send:\n");
String mess = sc.next(); 
System.out.println("Enter anything after you have scanned the QR");
String a = sc.next();

driver.findElement(By.xpath("//span[@title='Rinmay AEI']")).click();

我希望放置我的用户输入 name 字符串而不是“Rinmay AEI”

【问题讨论】:

    标签: java selenium variables xpath css-selectors


    【解决方案1】:

    不要对 title 属性的值进行硬编码,而是将其设为变量,然后您可以使用以下任一Locator Strategies

    • cssSelector:

      System.out.println("Name:\n");
      String name = sc.nextLine();
      // other lines of code
      driver.findElement(By.cssSelector("span[title='" + name + "']")).click();
      
    • xpath:

      System.out.println("Name:\n");
      String name = sc.nextLine();
      // other lines of code
      driver.findElement(By.xpath("//span[@title='" + name + "']")).click();
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-25
      • 1970-01-01
      • 2020-06-20
      相关资源
      最近更新 更多