如何在Selenium和Java中传递变量字符串到xpath以识别元素。

huangapple 未分类评论42阅读模式
英文:

How to pass a variable string within the xpath to identify an element in Selenium and Java

问题

如何在Selenium和Java中传递变量字符串到xpath中以识别元素

代码尝试

    System.out.println("姓名:");
	String name = sc.nextLine();
	System.out.println("输入消息数量:");
	int count = sc.nextInt();
	System.out.println("输入要发送的内容:");
	String mess = sc.next(); 
	System.out.println("扫描完QR码后输入任何内容:");
	String a = sc.next();

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

我希望将用户输入的`name`字符串放在`Rinmay AEI`的位置
英文:

How to pass a variable string within the xpath to identify an element in Selenium and Java?

Code trials:

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

I want my user input name String to be placed instead of 'Rinmay AEI'

答案1

得分: 0

代替在代码中硬编码 _title_ 属性的值,将其作为一个变量,并且您可以使用以下任一[定位策略](https://stackoverflow.com/questions/48369043/official-locator-strategies-for-the-webdriver/48376890#48376890):

- `cssSelector`:

    System.out.println("姓名:\n");
    String name = sc.nextLine();
    // 其他代码行
    driver.findElement(By.cssSelector("span[title='" + name + "']")).click();

- `xpath`:

    System.out.println("姓名:\n");
    String name = sc.nextLine();
    // 其他代码行
    driver.findElement(By.xpath("//span[@title='" + name + "']")).click();
英文:

Instead of hardcoding the value of title attribute, make it a variable and and you can use either of the following 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();
    

huangapple
  • 本文由 发表于 2020年7月27日 00:05:13
  • 转载请务必保留本文链接:https://java.coder-hub.com/63102570.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定