[英]xPath Text Contains Selenium Web Driver
I'm trying to select an element based on its text contents.我正在尝试根据其文本内容选择一个元素。 I am using XPath to achieve this.我正在使用 XPath 来实现这一点。
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:我什至会复制 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>
The div element has the words "Notifications" inside it. div 元素中包含“通知”字样。 So why doesn't it work.那么为什么它不起作用。
Go to this page on Facebook: https://www.facebook.com/settings在 Facebook 上访问此页面: https : //www.facebook.com/settings
Use this chrome extension to highlight any area via xPath.使用此chrome 扩展程序通过 xPath 突出显示任何区域。
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')]"));
I found the issue with the help of some amazing people in this community.我在这个社区中一些了不起的人的帮助下发现了这个问题。
Ok, so my element was in an iFrame.好的,所以我的元素在 iFrame 中。
In order to access the element, I must first access the iFrame为了访问元素,我必须首先访问 iFrame
WebElement iframe = obj.driver.findElement(By.xpath("//iframe[@tabindex='-1']"));
obj.driver.switchTo().frame(iframe);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.