Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select the first li element in selenium test?

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.

like image 556
Anthony Kong Avatar asked Feb 10 '23 23:02

Anthony Kong


2 Answers

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
like image 88
alecxe Avatar answered Feb 15 '23 10:02

alecxe


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.

like image 29
Mayur Shah Avatar answered Feb 15 '23 09:02

Mayur Shah