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.
CodePudding user response:
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];
CodePudding user response:
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