Selenium - wait until presence of child element of another element

时间:2017-04-09 23:21:39

标签: python selenium selenium-webdriver webdriver

I just started using the selenium, but after reading the docs I wasn't able to understand how to properly perform a wait (using EC) until webdriver identifies presence of an element which is a child of another element.

Let me explain. I want a specific element which I can access in 2 steps:

#find major group
listings = driver.find_element_by_id("new-listings");

#find subelement
checkbox = listings.find_element_by_class_name("listing-category")

That's OK, but I want to use EC to ensure that the checkbox is present. I cannot use smth like:

checkbox = driver.wait.until(EC.presence_of_element_located(
                (By.CLASS_NAME, "listing-category")))

Just because there is a bunch of other similar listing-category elements. And sadly the only way to locate checkbox is through the nested request like illustrated earlier (it doesn't have any id or whatever).

How to properly express it?

Small extra question: in general, is it very bad for performance to use EC instead of just hitting elements and hope that they are already available? 99% of the time I will not need to wait for element to appear, so I just try to handle rare situation when browser is less responsive than usual. But I am not sure if EC introduces significant overhead for just creating the event handler etc.

1 个答案:

答案 0 :(得分:1)

I would suggest that you use a CSS selector to accomplish this in one go. You can use the method you are describing but with a CSS selector you can find the child of an element with a single locator. In this case the CSS selector would be #new-listings .listing-category. In CSS selectors, # indicates an ID and . indicates a class name. The space between the two parts indicates a descendant. If you wanted a child (a direct descendant), you would use >, e.g. #new-listings > .listing-category.

To your question about EC and performance, no it doesn't slow things down. It always checks immediately to see if the condition is true, if it's not then it waits so it generally doesn't hurt to add a wait.

If you are new to CSS selectors, here are some links that you can read up on and learn about them. They are very powerful and quick locators.

CSS selector reference

CSS selector tips

Advanced CSS selectors