ttarter3
ttarter3

Reputation: 83

Using Python Selenium, how to do click on a webElement of webElements?

I have figured out how to find a subelement of an element using Selenium in python using this Stack overflow post.

Selenium Get WebElement inside a WebElement

I want to take it one step further. I want to be able to perform actions on the subelement. Going off the previous example:

<div class='wrapper'>
  <div class='insider1'>
  <div class='insider2'>
<div class='wrapper'>
  <div class='insider1'>
  <div class='insider2'>

I am trying to do something like

elements = driver.find_elements_by_xpath('//div')
for element in elements:
    sub_element = element.find_element_by_xpath('//div')
    if sub_element.is_displayed()
        ActionChains(driver) \
            .move_to_element(sub_element ) \
            .click(sub_element ) \
            .perform()

Yes, I could just do sub_element.click() in this example but I want to do more types of interactions.

The example as is cannot find the element subelement. And if I put ActionChains(element) instead of ActionChains(driver), the code throws an error because element is a webElement and not a webDriver.

Upvotes: 3

Views: 310

Answers (1)

Bongni
Bongni

Reputation: 133

First of all you have to close your html tags:

<div class='wrapper'>
  <div class='insider1'></div>
  <div class='insider2'></div>
</div>
<div class='wrapper'>
  <div class='insider1'></div>
  <div class='insider2'></div>
</div>

And to select the inner tags I used this code:

outers = driver.find_elements_by_xpath('//div[@class="wrapper"]')

for outer in outers:
    inners = outer.find_elements_by_xpath('./child::div')
    for inner in inners:
        print(inner)

You specify the class of the outer div's with:

'//div[@class="wrapper"]'

This way you don't accidentally select the inner one's as I think it happened with your code. Then you select all child elements of outer that are div's:

'./child::div'

Upvotes: 1

Related Questions