0

When I inspect the second div in Chrome, I see a new calculated property "text 1". How can I select the second div by this calculated property?

<html>
<body>

<div id="a">text 1</div>
<div aria-labelledby='a'>text 2</div>

</body>
</html>

i tried without success

element = browser.find_element_by_xpath("//div[@'text 1']")
Lorenz
  • 266
  • 1
  • 5
  • 16

3 Answers3

1

As I understood, your goal to get <div aria-labelledby='a'>text 2</div> referenced to the <div id="a">text 1</div> by id and aria-labelledby.
Solution is to find element by text 1 text, get id attribute and use it to search second div with aria-labelledby attribute:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec

driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)

driver.get("some url")

id = wait.until(ec.visibility_of_element_located((By.XPATH, "//div[.='text 1']"))).get_attribute("id")
text2 = driver.find_element_by_css_selector(f"div[aria-labelledby='{id}']").text
# text2 = driver.find_element_by_xpath(f"//div[@aria-labelledby='{id}']").text
labelled_elements = driver.find_elements_by_xpath(f"//div[@aria-labelledby='{id}']")
Sers
  • 12,047
  • 2
  • 12
  • 31
  • Thanks, that works and is a great solution. Is there no way to do this viaa xpath directive? Or a built in fiunction in selenium? I almost can't believe this. – Lorenz Sep 29 '19 at 12:01
  • This is the only way – Sers Sep 29 '19 at 12:05
  • Ok, thanks for confirming. In my real life case, the labelled by is composed of multiple ids. Is it possible to change your last line in a way, that the xpath selects all elements where the id is *contained* in the labelledby? – Lorenz Sep 29 '19 at 12:12
  • That works. I used a slightly updated version with a 'contained' statement: labelled_elements = driver.find_elements_by_xpath(f"//div[contains(@aria-labelledby, '{id}') – Lorenz Oct 06 '19 at 16:03
0

You could use browser.find_element_by_xpath("//div[text()='text 1']")//following-sibling::div

This just retrieves the div following another div with text property text 1.

CEH
  • 5,701
  • 2
  • 16
  • 40
  • This gives me the first div, but I want to get the second by referencing to "text 1" (which is the link between the two) – Lorenz Sep 29 '19 at 00:58
  • This XPath specifies that `text` equals `text 1`. Are there multiple divs on the page that share this same text value? – CEH Sep 29 '19 at 05:10
  • I want to get the second div, *but* the only information I have is "text 1", which belongs to another div. both divs are linked through a labelledby. – Lorenz Sep 29 '19 at 12:04
  • Makes sense. Updated my answer to get second div in this case. – CEH Sep 29 '19 at 14:59
0

xpath expression //div[@aria-labelledby = //div[.='text 1']/@id]/text() gives you "text 2" directly