Home > Mobile >  How to search for an element inside another one with selenium
How to search for an element inside another one with selenium

Time:08-04

I am searching for elements that contains a certain string with find_elements, then for each of these elements, I need to ensure that each one contain a span with a certain text, is there a way that I can create a for loop and use the list of elements I got?

today = self.dataBrowser.find_elements(By.XPATH, f'//tr[child::td[child::div[child::strong[text()="{self.date}"]]]]')

CodePudding user response:

I believe you should be able to search within each element of a loop, something like this:

today = self.dataBrowser.find_elements(By.XPATH, f'//tr[child::td[child::div[child::strong[text()="{self.date}"]]]]')

for element in today:
    span = element.find_element(By.TAG_NAME, "span")

    if span.text == "The text you want to check":
        ...do something...

Let me know if that works.

CodePudding user response:

Sure, you can.
You can do something like the following:

today = self.dataBrowser.find_elements(By.XPATH, f'//tr[child::td[child::div[child::strong[text()="{self.date}"]]]]')
for element in today:
    span = element.find_elements(By.XPATH,'.//span[contains(text(),"the_text_in_span")]')
    if !span:
        print("current element doesn't contain the desired span with text")

To make sure your code doesn't throw exception in case of no span with desired text found in some element you can use find_elements method. It returns a list of WebElements. In case of no match it will return just an empty list. An empty list is interpreted as a Boolean false in Python while non-empty list is interpreted as a Boolean true.

  • Related