Unable to locate element | xPath | Selenium Webdriver

旧城冷巷雨未停 提交于 2021-01-29 08:31:24

问题


I am trying to reference and then click an element on a web page.

This is the web page: https://www.facebook.com/settings

This is the element:

<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>

It's a DIV which contains the word "Notifications"

We should be able to reference with a simple xPath. Such as //div[contains(text(), 'Notifications')]

However, it doesn't seem to work.

A chrome extension I use says the element doesn't exist.

My code can't find the element.

Here is my Java code using Selenium web driver.

// Navigate to page
obj.driver.get("https://www.facebook.com/settings");        

// Write to console where we are
System.out.println(obj.driver.getCurrentUrl());

// Wait | Plenty of time for the page to load
Thread.sleep(5000);     

obj.driver.findElement(By.xpath("//div[contains(text(), 'Notifications')]")).click();

Here is the error:

It is so very strange! Any ideas on why I can't reference the element, or why the xPath doesn't exsist.


回答1:


Your element is within an iframe.

If you scroll up from where you are you'll see this:

For selenium you need to switch frames in order to access the elements within them

I've not tried it for your site yet - but you switch frames with:

driver.switchTo().frame(1); // by index
//<or> 
driver.switchTo().frame("id of the element"); //by id
//<or> 
driver.switchTo().frame(element); // be element

Then, when ready switch back to the main page/frame with:

  driver.switchTo().defaultContent();

Have a look at the frames section of the selenium docs here



来源:https://stackoverflow.com/questions/64597085/unable-to-locate-element-xpath-selenium-webdriver

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!