Handling Dynamic Xpath

后端 未结 6 480
心在旅途
心在旅途 2021-01-06 18:49

Am automating things using Selenium. Need your help to handle Dynamic Xpath as below:

Driver.findElement(By.xpath(\"//[@id=\'INQ_2985\']/div[2]/tr/td/div/div[3

相关标签:
6条回答
  • 2021-01-06 19:11

    Good to use Regular expression

    driver.findElement(By.xpath("//*[contains(@id,'INQ_')]")
    

    Note: If you have single ID with name starts from INQ_ then you can take action on the element . If a bunch of ID then you can extract as a List<WebElements> and then match with the specific text of the element ( element.getText().trim() =="Linked Text" and if it matched then take action. You can follow other logic to traverse and match.

    0 讨论(0)
  • 2021-01-06 19:13

    you can use many methods, use implicity wait;

    driver.findElement(By.xpath("//*[contains(@id,'select2-result-label-535')]").click();
    
    driver.findElement(By.xpath("//*[contains(text(), 'select2-result-label-535')]").click();
    
    0 讨论(0)
  • 2021-01-06 19:16

    you can use css -

    div.context-menu-item-inner
    

    Use this xpath:

    driver.findElement(By.cssSelector("div.context-menu-item-inner").click();
    
    0 讨论(0)
  • 2021-01-06 19:23

    The best choice is using full xpath instead of id which you can get easily via firebug.

    e.g.

    /html/body/div[3]/div[3]/div[2]/div/div[2]/div[1]/div/div[1]
    
    0 讨论(0)
  • 2021-01-06 19:23

    if your xpath is varying

    Ex: "//*[@id='msg500']" , "//*[@id='msg501']", "//*[@id='msg502']" and so on...

    Then use this code in script:

    for (int i=0;i<=9;i++) {
    String mpath= "//*[@id='msg50"+i+"']";
    driver.findElement(By.xpath(mpath)).click();
    }
    
    0 讨论(0)
  • 2021-01-06 19:28

    you can try using contains() or starts-with() in xpath,

    above xpath can be rewritten as follows,

    Driver.findElement(By.xpath("//*[starts-with(@id,'INQ')]/div[2]/tr/td/div/div[3]/div")).click();

    if you can post more of your html, we can help improve your xpath..

    • moreover using such long xpath's is not recommended, this may cause your test to fail more often

    for example,if a "new table data or div" is added to the UI, above xpath will no longer be valid

    • you should try and use id, class or other attributes to get closer to the element your trying to find
    • i personally recommend using cssSelectors over xpath
    0 讨论(0)
提交回复
热议问题