如何在webdriver中获取多个Web元素的相对xpath?

时间:2017-02-01 07:23:39

标签: xpath selenium-webdriver

<a id="ctl00_cphBody_gvMessageList_ctl02_hlnkMessageSubject" href="Message.aspx?id=3428&member=">DDM IT QUIZ 2017 – Bhubaneswar Edition</a>

<a id="ctl00_cphBody_gvMessageList_ctl03_hlnkMessageSubject" href="Message.aspx?id=3427&member=">[Paybooks] Tax/investment declaration proof FY 2016-17</a>

<a id="ctl00_cphBody_gvMessageList_ctl04_hlnkMessageSubject" href="Message.aspx?id=3426&member=">Reimbursement clarification</a>

出:

DDM IT QUIZ 2017 – Bhubaneswar Edition

[Paybooks] Tax/investment declaration proof FY 2016-17

Reimbursement clarification

如何获取这三个元素的相对xpath,以便我可以获得上述文本。

3 个答案:

答案 0 :(得分:0)

xpath = '//a/text()'

这将返回文本列表

答案 1 :(得分:0)

完整的答案是:

  • 获取相同类型的所有a元素,在这种情况下,id包含ctl00

    // a [contains(@ id,'ctl00')]

  • 您可以添加更多限制,例如添加href限制,以在其值中包含某个字符串

    // a [contains(@ id,'ctl00')] [contains(@href,'Message')]

  • 获取所有a元素就足以使用

    //一个

为了获取文本,您可以使用方法从框架中获取文本或将/text()添加到xpath表达式。

答案 2 :(得分:0)

您可以使用span类[relative xpath],如下例所示,以及鼠标操作和键盘操作。 看看这个,让我知道!

 import java.util.concurrent.TimeUnit;
 import org.openqa.selenium.By;
 import org.openqa.selenium.Keys;
 import org.openqa.selenium.WebDriver;
 import org.openqa.selenium.WebElement;
 import org.openqa.selenium.firefox.FirefoxDriver;
 import org.openqa.selenium.interactions.Actions;  

 public class SnapD {  
 public static void main(String args[]){  
 WebDriver d=new FirefoxDriver();  
 d.get("https://www.snapdeal.com/");
 d.manage().window().maximize();
 d.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
 System.out.println("Hello Google...");  
 System.out.println("Hello Snapdeal...");
 WebElement wb= d.findElement(By.xpath("//span[text()='Electronics']"));
 Actions act=new Actions(d);
 act.moveToElement(wb);
 act.perform();
 System.out.println("Mouse hovered");
 WebElement wb1=d.findElement(By.xpath("//span[text()='DTH Services']"));
 act.contextClick(wb1).perform();
 act.sendKeys(Keys.ARROW_DOWN,Keys.ENTER).perform();
 act.sendKeys(Keys.chord(Keys.CONTROL,Keys.TAB)).perform();  

 }  
 } 
相关问题