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?