2010-11-14 5 views

Répondre

9

pas directement de WebDriver, mais vous pouvez faux si vous avez vraiment besoin:

public String getElementXPath(WebDriver driver, WebElement element) { 
    return (String)((JavascriptExecutor)driver).executeScript("gPt=function(c){if(c.id!==''){return'id(\"'+c.id+'\")'}if(c===document.body){return c.tagName}var a=0;var e=c.parentNode.childNodes;for(var b=0;b<e.length;b++){var d=e[b];if(d===c){return gPt(c.parentNode)+'/'+c.tagName+'['+(a+1)+']'}if(d.nodeType===1&&d.tagName===c.tagName){a++}}};return gPt(arguments[0]).toLowerCase();", element); 
} 

Le Javascript est de this post, minified pour tenir sur une seule ligne. Ce n'est peut-être pas parfait, mais cela pourrait vous donner une idée de l'endroit où aller. La plupart des pilotes implémentent l'interface JavascriptExecutor et ont la capacité d'exécuter Javascript dans le navigateur. executeScript peut renvoyer un type JavaScript primitif, un élément HTML ou une liste non imbriquée de l'un des éléments précédents.

Not all browsers support xpath the same way, donc soyez prudent si vous utilisez ces xpaths pour sélectionner des éléments. En outre, tous les navigateurs n'ont pas de support xpath natif (toux IE toux), donc il a été truqué dans ce cas.

+0

C'est awersome :) fonctionne parfaitement avec Chrome 62. Merci :) dflems –

1
public String getElementXPath(WebDriver driver, WebElement element) { 

    String javaScript = "function getElementXPath(elt){" + 
          "var path = \"\";" + 
          "for (; elt && elt.nodeType == 1; elt = elt.parentNode){" + 
           "idx = getElementIdx(elt);" + 
           "xname = elt.tagName;" + 
           "if (idx > 1){" + 
            "xname += \"[\" + idx + \"]\";" + 
           "}" + 
           "path = \"/\" + xname + path;" + 
          "}" + 
          "return path;" + 
         "}" + 
         "function getElementIdx(elt){" + 
          "var count = 1;" + 
          "for (var sib = elt.previousSibling; sib ; sib = sib.previousSibling){" + 
           "if(sib.nodeType == 1 && sib.tagName == elt.tagName){" + 
            "count++;" + 
           "}" + 
          "}" + 
          "return count;" + 
         "}" + 
         "return getElementXPath(arguments[0]).toLowerCase();";  

    return (String)((JavascriptExecutor)driver).executeScript(javaScript, element);  

} 
+1

la signature de la méthode ci-dessus ne rentre pas dans la zone grisée alors assurez-vous de faire attention à cela ... – Michael

2

Les deux réponses ci-dessus souffrent du même problème. En renvoyant le XPath complété avec la fonction .toLowerCase() appelée, tout XPath contenant un ID avec une lettre majuscule ne fonctionnera pas.

Exemple: //div[@id="deviceblock-1111"] ne fonctionnera pas sur l'étiquette <div id="deviceBlock-1111">

Vous pouvez cependant supprimer juste le .toLowerCase() appel de retour, mais vous finirez par la recherche de XPath comme ceci: //DIV[@id="deviceBlock-1111"]/DIV[2]/SELECT[1]/OPTION[5]

Pour résoudre cela, utilisez les fonction ci-dessous. Cela retournera un XPath unique correctement formaté à partir de votre WebElement.

//div[@id="deviceBlock-1111"]/div[2]/select[1]/option[5]

0

Il est un moyen d'obtenir les éléments XPath sans l'utilisation de JavaScript.

  1. Définir le point de départ du XPath externe, par exemple l'étiquette du corps.
  2. Vérifiez toutes les étiquettes internes possibles avec du sélénium pour NoSuchElementException.
  3. Vérifiez getText pour les listes de XPath générées.
  4. victoire
4

Si WebElement a été trouvé par By.xpath: sur Java:

public static String GetWebElementXpath(WebElement El) throws AssertionError{ 
     if ((El instanceof WebElement)){ 
      Object o = El; 
      String text = o.toString(); 
     /* text is smth like this 
     [[FirefoxDriver: firefox on WINDOWS (9170d4a5-1554-4018-adac-f3f6385370c0)] -> xpath: //div[contains(@class,'forum-topic-preview')]//div[contains(@class,'small-human')]] 
     */ 
      text = text.substring(text.indexOf("xpath: ")+7,text.length()-1); 
      return text; 
     }else { Assert.fail("Argument is not an WebElement, his actual class is:"+El.getClass());  } 
     return ""; 
    } 
0
public static String getXPathFromElement(WebElement element) { 
     String elementDescription = element.toString(); 
     return elementDescription.substring(elementDescription.lastIndexOf("-> ") + 3, elementDescription.lastIndexOf("]")); 
} 

élément Web toString() ressemble à ceci:

« [[ FirefoxDriver: firefox sous WINDOWS (ceb69f9f-bef4-455d-b626-ab439f195be6)] -> id: pageBeanfundDescription] '

Je viens d'extraire le id/xpath.

0
/** 
* This method return By reference for the WebElement passed to it as a parameter. 
* @param element 
* @return 
*/ 
public static By convertWebElementToByReference(WebElement element) 
{ 
    By byLocator = null; 
    String elementDescription = element.toString(); 
    String elementTypeAndValue[] = (elementDescription.substring(elementDescription.lastIndexOf("-> ") + 3, elementDescription.lastIndexOf("]"))).split(":");   

    switch (elementTypeAndValue[0].trim()) 
    { 
     case "id": byLocator = By.id(elementTypeAndValue[1].trim()); 
      break; 

     case "xpath": byLocator = By.xpath(elementTypeAndValue[1].trim()); 
      break; 

     case "link text": byLocator = By.linkText(elementTypeAndValue[1].trim()); 
      break; 

     case "tag name": byLocator = By.tagName(elementTypeAndValue[1].trim()); 
      break; 

     case "class name": byLocator = By.className(elementTypeAndValue[1].trim()); 
      break; 

     case "partial link text": byLocator = By.partialLinkText(elementTypeAndValue[1].trim()); 
      break; 

     case "name": byLocator = By.name(elementTypeAndValue[1].trim()); 
      break; 

     case "css selector": byLocator = By.cssSelector(elementTypeAndValue[1].trim()); 
      break; 

     default: 
      throw new RuntimeException("Invalid locator type: " + elementTypeAndValue[0].trim()); 
    } 

    return byLocator; 
} 
+0

S'il vous plaît inclure une description avec l'exemple de code. –

0

Je commentaires directement sur dflems 'answer, mais je n'ai pas la réputation de le faire.

La conversion de l'intégralité de xpath en minuscules est correcte à moins que le xpath ne contienne une valeur d'identifiant qui ne soit pas toute minuscule. Voici une version modifiée de dflems de Javascript, mais en Python au lieu de Java:

def get_xpath_from_element(driver, element): 
    return driver.execute_script("gPt=function(c){if(c.id!==''){return'id(\"'+c.id+'\")'}if(c===document.body){return c.tagName}var a=0;var e=c.parentNode.childNodes;for(var b=0;b<e.length;b++){var d=e[b];if(d===c){return gPt(c.parentNode)+'/'+c.tagName.toLowerCase()+'['+(a+1)+']'}if(d.nodeType===1&&d.tagName===c.tagName){a++}}};return gPt(arguments[0]);", element) 

Questions connexes