英文:
xPath Text Contains Selenium Web Driver
问题
我正在尝试根据元素的文本内容选择元素。我正在使用XPath来实现这一点。
我感到困惑,因为这应该有效?
WebElement link = obj.driver.findElement(By.xpath("//div[contains(text(), 'Notifications')]"));
我甚至会复制HTML代码:
<div class="linkWrap noCount">Notifications&nbsp;<span class="count _5wk0 hidden_elem uiSideNavCountText">(<span class="countValue fsm">0</span><span class="maxCountIndicator"></span>)</span></div>
div元素内部有文字“Notifications”。那么为什么它不起作用呢?
访问Facebook上的此页面:https://www.facebook.com/settings
使用此Chrome扩展通过xPath突出显示任何区域。
英文:
I'm trying to select an element based on its text contents. I am using XPath to achieve this.
I am just puzzled as this should work?
WebElement link = obj.driver.findElement(By.xpath("//div[contains(text(), 'Notifications')]"));
I'll even copy the HTML code:
<div class="linkWrap noCount">Notifications&nbsp;<span class="count _5wk0 hidden_elem uiSideNavCountText">(<span class="countValue fsm">0</span><span class="maxCountIndicator"></span>)</span></div>
The div element has the words "Notifications" inside it. So why doesn't it work.
Go to this page on Facebook: https://www.facebook.com/settings
Use this chrome extension to highlight any area via xPath.
答案1
得分: 0
你在单词“Notifications”之前有一个空格:
WebElement link = obj.driver.findElement(By.xpath("//div[contains(text(), 'Notifications')]"));
在尝试查找该元素之前,你还应该添加等待元素可见的操作:
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')]"));
英文:
You have a space before the word Notifications:
WebElement link = obj.driver.findElement(By.xpath("//div[contains(text(), 'Notifications')]"));
You should also add a wait for element before trying to find the element:
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')]"));
答案2
得分: 0
我在这个社区里得到了一些了不起的人的帮助,找到了问题所在。
好的,所以我的元素位于一个 iFrame 中。
为了访问这个元素,我必须首先访问这个 iFrame。
WebElement iframe = obj.driver.findElement(By.xpath("//iframe[@tabindex='-1']"));
obj.driver.switchTo().frame(iframe);
英文:
I found the issue with the help of some amazing people in this community.
Ok, so my element was in an iFrame.
In order to access the element, I must first access the iFrame
WebElement iframe = obj.driver.findElement(By.xpath("//iframe[@tabindex='-1']"));
obj.driver.switchTo().frame(iframe);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论