Selenium Webdriver:如何使用xpath获取动态id?

时间:2015-11-03 12:40:42

标签: java selenium xpath

我正在尝试获取以'u_'开头并以'_5'结尾的元素的id以及按字母顺序更改数据之间的内容。因此,有时我会看到'u_d_5'而有时'u_6_5'。在那种情况下,如何获得动态ID? 我知道有一些方法,比如开始或结束,但它们根本不适用于我。有人可以在这个建议我一些想法吗? 代码段:

WebElement cls=ff.findElement(By.xpath("//*[@id='u_6_5']"));

整个代码:

    String s=System.getProperty("user.dir");
    System.setProperty("webdriver.chrome.driver", s+"\\ChromeDriver\\chromedriver.exe");
    ChromeDriver ff=new ChromeDriver();
try{
    ff.manage().window().maximize();
    ReadfrmExcel rd=new ReadfrmExcel();//reading data
    String[][] readata=rd.excelRead();
    for(int i=1; i<readata.length; i++)
    {
    ff.get("http://www.facebook.com");
    Thread.sleep(1000);
    ff.findElementByXPath("//*[@id='email']").sendKeys(readata[i][0]);
    ff.findElementByXPath("//*[@id='pass']").sendKeys(readata[i][1]);
    ff.findElement(By.id("u_0_v")).click();
    System.out.println("Waiting for element to appear");
    Thread.sleep(3000);
    WebElement element=ff.findElement(By.id("userNavigationLabel"));
    element.click();
    System.out.println("Clicked drop down");
    //ff.findElementByXPath("//*[@id='userNavigationLabel']").click();
    System.out.println("sleeping 5 secs");
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
        WebElement cls=ff.findElement(By.xpath("//*[starts-with(@id,'u_')   and ends-with(@id, '_5']"));
    boolean vis=cls.isDisplayed();

    System.out.println(vis);
    Thread.sleep(8000);
    System.out.println("Sleeping 8 secs");
    cls.click();
    System.out.println("After clicking");

    System.out.println("Successfully logged out!!");
    //ff.close();
    ff.close();

    }
    }
    catch(Exception e){
        System.out.println(e);
    }

2 个答案:

答案 0 :(得分:2)

您可以使用xpath的starts-withends-with方法:

WebElement cls=ff.findElement(By.xpath("//*[starts-with(@id,'u_') and ends-with(@id, '_5')]"));

如果这不起作用,您的浏览器可能只支持xpath 1.0(有关详细信息,请参阅this answer) - &gt;那么你只能使用start-with

WebElement cls=ff.findElement(By.xpath("//*[starts-with(@id,'u_')]"));

如果您确实需要检查id的结尾,那么您可以尝试使用以下xpath:

//*[starts-with(@id, 'u_') and substring(@id, string-length(@id) - 1) = '_5']

答案 1 :(得分:0)

我试图获得所有ID,我必须使用它。 首先获取已定义id属性的标记名称。

java.util.List links = ff.findElements(By.tagName(&#34; span&#34;));

ArrayList arrList = new ArrayList();

for(int i = 0; i&lt; links.size(); i ++){

   if(links.get(i).getAttribute("id").startsWith("u_") && 
          links.get(i).getAttribute("id").endsWith("_5")){
                arrList.add(links.get(i).getAttribute("id"));
            }
        }

  Now you will find all the ids which are starts with "u_" and ends with"_5".

 System.out.println("arrList elements : "+arrList);