1

I have a page that has code designed as given below. From this, using automation id I would like to get values '6' and 'ft' separately.

<span class="something" ....>
    <span abcdef automation-id="xyz"> My height is 6 ft </span>
</span>

I saw this question, which helps to some extent. The solution given by Qharr here makes sense. How to locate an element and extract required text with Selenium and Python I'm trying to find elements in a similar way by using automation id and get values '6' and 'ft' by using, maybe + operator for sibling values?

WebElement x = driver.find_element_by_css_selector(use automation id)+ .... 

So basically in one above the line, I would like x to capture value '6' and use a different webelement say y to capture value 'ft' in one line of code.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
stuart
  • 47
  • 1
  • 7
  • Show us what you have tried and what the problem is. – Scary Wombat Nov 11 '21 at 02:18
  • @stuart As per your code trials`driver.find_element_by_css_selector()` and the linked discussion, I've replaced the Java tag with Python tag. Let me know if the change is as per your requirement or else I will revert back the change. – undetected Selenium Nov 11 '21 at 09:22

2 Answers2

1

You can try this way:

WebElement x = driver.find_element_by_css_selector(use automation id)+ .... ;


String info = x.getText();

String[]y = info.split(" ");

String height = y[y.length-2];
String weightMeter = y[y.length-1];
Norayr Sargsyan
  • 1,737
  • 1
  • 12
  • 26
1

First you have to extract the phrase My height is 6 ft and then split the text/string into a list using split(). Now you can print the desired element from the list as per their respective position as follows:

print("Number: " + WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[@automation-id='xyz']"))).text.split()[-2])
print("Units: " + WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//span[@automation-id='xyz']"))).text.split()[-1])

Console Output:

Number: 6
Units: ft

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352