'How to locate a nested element by using Selenium webdriver?
I have the following html:
<label class="control-label col-sm-4" for="bla-bla">
"Value date"
::after
</label>
<div class="col-sm-8">
<div class="row">
::before
<div class="col-sm-2>
<label class="control-label" for="bla-bla">
"Priority"
::after
</label>
</div>
::after
</div>
::after
</div>
I need to extract both the elements like "Value date" and the "Priority" element. Here is my current solution:
elements = [f for f in driver.find_elements(By.XPATH, "//*[contains(@class, 'control-label')]")]
It works perfectly with the elements like "Value date", but it doesn't see the "Priority" element. I see that "Priority" is nested in the "Value date" element here. Maybe, it somehow affects the way XPATH works. I tried adding the exact class match, but without any result:
elements = [f for f in driver.find_elements(By.XPATH, "//*[contains(@class, 'control-label') or @class = 'control-label']")]
Solution 1:[1]
Actually the XPATH was working OK. The problem was in what I was doing with the found elements next. I was extracting text by using the .text() method which doesn't always work as expected. If you experience similar problems, try using .get_attribute('innerText') and .get_attribute('textContent').
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Denis |
