xPath Text contient le pilote Web Selenium
J'essaie de sélectionner un élément en fonction de son contenu textuel. J'utilise XPath pour y parvenir.
Je suis juste perplexe car cela devrait fonctionner?
WebElement link = obj.driver.findElement(By.xpath("//div[contains(text(), 'Notifications')]"));
Je vais même copier le code HTML:
<div class="linkWrap noCount">Notifications <span class="count _5wk0 hidden_elem uiSideNavCountText">(<span class="countValue fsm">0</span><span class="maxCountIndicator"></span>)</span></div>
L'élément div contient les mots "Notifications". Alors pourquoi ça ne marche pas.
Allez sur cette page sur Facebook: https://www.facebook.com/settings
Utilisez cette extension chrome pour mettre en évidence n'importe quelle zone via xPath.
Réponses
Vous avez un espace avant le mot Notifications:
WebElement link = obj.driver.findElement(By.xpath("//div[contains(text(), 'Notifications')]"));
Vous devez également ajouter une attente d'élément avant d'essayer de trouver l'élément:
WebDriverWait wait = new WebDriverWait(webDriver, timeoutInSeconds);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(text(), 'Notifications')]"));
WebElement link = obj.driver.findElement(By.xpath("//div[contains(text(), 'Notifications')]"));
J'ai trouvé le problème avec l'aide de personnes extraordinaires dans cette communauté.
Ok, donc mon élément était dans un iFrame.
Pour accéder à l'élément, je dois d'abord accéder à l'iFrame
WebElement iframe = obj.driver.findElement(By.xpath("//iframe[@tabindex='-1']"));
obj.driver.switchTo().frame(iframe);