5

The structure of the tags is shown in the screenshot

enter image description here

I am trying to use this python code to access the first li element:

invitations = elem.find_element_by_css_selector('members-holder li#invitation-holder > :first-child')

elem is a very top level element that contains all the tags

I got this exception:

NoSuchElementException: Message: Unable to locate element: {"method":"css selector","selector":"members-holder li#invitation-holder > :first-child"}

I have tried a few variation but cannot get the result I want. What is the best way to select the said element?

EDIT

I have tried an alternative css selector .members-holder .invitation-holder:first-child in developer console in chrome and it works. But when I plug it in the python selenium code, the same exception is thrown.

4
  • i think it is el.find , not elem.find
    – m0bi5
    Feb 9, 2015 at 6:26
  • Is it under any frame/iframe? or does it take time to load ? Feb 9, 2015 at 6:30
  • @VivekSingh You have a very good point! It is hidden at the very beginning Feb 9, 2015 at 6:32
  • Then you can use wait condition for visibility. Happy to help.. Feb 9, 2015 at 6:50

2 Answers 2

6

First of all, you should fix your CSS selector:

.members-holder ul li.invitation-holder

And, since you need the first li, just use the find_element_by_css_selector() method:

driver.find_element_by_css_selector('.members-holder ul li.invitation-holder')

Aside from that, you may need to explicitly wait for the element to become visible:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

...
element = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.CSS_SELECTOR, ".members-holder ul li.invitation-holder"))
)

If you would still get an exception trying to reach the element, check if an element is inside an iframe - if yes, switch to it first:

frame = driver.find_element_by_id('frame_id')
driver.switch_to.frame(frame)

# find the element
1
  • the switch_to.frame('id') hint was especially useful!
    – ccpizza
    Oct 6, 2017 at 13:12
3

Try to identify element using this way.

WebElement parentDiv = driver.findElement(By.className("'members-holder"));

now Do

WebElement ul = parentDiv.findElement(By.tagName("ul"));
List<WebElement> lis = ul.findElements(By.tagName("li"));

First element is

lis.get(0);

This is java code. You can workout equilent in python. Hope it helps.

1
  • How's WebElement ul = parentDiv.findElements(By.tagName("ul")); returns the a SINGLE element? It should return a list
    – Saifur
    Feb 13, 2015 at 17:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.