Search code examples
pythonselenium-webdrivertextlabel

How to get text following label in Selenium Python?


In this HTML, there is no uniquely identified wrapper. If the voice number and/or the fax number is there then the Phone Numbers: label will always be there. If there is no number then the associated label will never be there. If there is a number then the associated label will always be there, but the number will change:

<p>
<label>Phone Numbers:</label>
<br>
<label>Voice Number:</label>
" (321) 456-7890"
<br>
<label>Fax Number:</label>
" (123) 456-7890"
</p>

I want to get the text (the numbers) following the voice and fax labels.

I used:

driver.find_element(By.XPATH, '//label[text() = "Voice Number:"]')

and

driver.find_element(By.XPATH, '//label[text() = "Fax Number:"]')

to find the labels but I want to get the text (the numbers) following the labels. I found plenty of direction on how to get the text of a label, but nothing that worked in this situation on how to get the text following a label. What code should I be using to get the text following the label in this situation? Thanks in advance.


Solution

  • Fax itself is not the text of your label, it's text of parent element. So, you need to parse text of parent element get fax number.

    If parent doesn't have unique attribute, you can:

    1. search by label
    2. get it's parent
    3. get parent text
    4. split it by your search term
    5. get the last array element (it would be your fax number)
    search_text = 'Fax Number:'
    fax = driver.find_element(By.XPATH, f'//label[text() = "{search_text}"]/..')
    fax_text = fax.text.split(search_text)[-1]
    

    You can test it there:

    url = "https://inputnum.w3spaces.com/saved-from-Tryit-2023-09-05.html"
    driver.get(url)