1

Suppose I have multiple div elements like the following:

<div style="background-color:#FFF4A3;">
  <h2>London</h2>
  <p>London is the capital city of England.</p>
  <p>London has over 9 million inhabitants.</p>
</div>

<div style="background-color:#FFC0C7;">
  <h2>Oslo</h2>
  <p>Oslo is the capital city of Norway.</p>
  <p>Oslo has over 700,000 inhabitants.</p>
</div>

<div style="background-color:#D9EEE1;">
  <h2>Rome</h2>
  <p>Rome is the capital city of Italy.</p>
  <p>Rome has over 4 million inhabitants.</p>
</div>

Suppose I want to find every h2 element, and then retrieve the text of its parent div (of course, in a full example, there would be divs without h2 elements, and h2 elements without divs, so looping over the divs directly is not a solution).

In SeleniumBase I came up with:

from seleniumbase import SB
from selenium.webdriver.common.by import By

with cm as SB(test=True, uc=True):
    sb.get("https://www.w3schools.com/html/tryit.asp?filename=tryhtml_div4")
    # accept choices
    sb.click("div#accept-choices")
    sb.switch_to_frame("iframe")
    for el in sb.find_elements("h2"):
        parent = el.find_element(By.XPATH, "..")
        print(parent.text, "\n---")

The problem is that find_elements seems to return raw Selenium WebElement objects, and so I have to use bare Selenium functions to interact with them (the Selenium find_element, which takes the type of selector as first parameter, and so on).

Is this the correct way to iterate over multiple elements in SeleniumBase?

If not, what is it?

1 Answer 1

1

Instead of trying to get the parent of the h2, (which is the div), you can instead use "div:has(h2)" as the selector:

from seleniumbase import SB

with SB(test=True, uc=True, pls="none", ad_block=True, sjw=True) as sb:
    url = "https://www.w3schools.com/html/tryit.asp?filename=tryhtml_div4"
    sb.open(url)
    sb.switch_to_frame("iframeResult")
    for el in sb.find_elements("div:has(h2)"):
        print(el.text, "\n---")

That prints out:

London
London is the capital city of England.
London has over 9 million inhabitants. 
---
Oslo
Oslo is the capital city of Norway.
Oslo has over 700,000 inhabitants. 
---
Rome
Rome is the capital city of Italy.
Rome has over 4 million inhabitants. 
---
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.