0

HTML:

<tr>
   <td class="formtext" colspan="3">
   <span class="required">*</span>
     Are you?
   </td>
   <td class="formtext" colspan="3">

   <input type="radio" value="M">
     Male
   <input type="radio" value="F">
     Female

   </td>
</tr>

Python:

browser.find_elements_by_xpath('//td[contains(text(),"Are you?")]')[0].find_elements_by_xpath('./following::td[contains(text(),"Male")]//preceding-sibling::input')[0].click() 

My current solution is working [0].click() = Male, [1].click() = "Female"

Question: Instead of using [0] and [1], how to set up so that if text() == "Male" the input before this text will be clicked, so this function will work based on TEXT

P.S. Please do not suggest using value (M/F), I need to make it work based on TEXT

I'm looking for something like this:

Male will be clicked

browser.find_elements_by_xpath('//td[contains(text(),"Are you?")]')[0].find_elements_by_xpath('./following::td[contains(text(),"Male")]//preceding-sibling::input')[0].click()

Female will be clicked

browser.find_elements_by_xpath('//td[contains(text(),"Are you?")]')[0].find_elements_by_xpath('./following::td[contains(text(),"Female")]//preceding-sibling::input')[0].click()

2 Answers2

1

You can use something like below in your xpath

//td/text()[contains(.,'Male')]/preceding-sibling::input[1]

This will give the text node which contains Male and then previous input for the same

Also if you are ok to use value you should using like below for selecting Male option

//td/input[@type='radio'][@value='M']
Tarun Lalwani
  • 142,312
  • 9
  • 204
  • 265
  • Please modify your answer as your current solution will not work for "Female". And this will work `//td/text()[contains(.,'Male')]/preceding-sibling::input[1]` – Oksana Krasiuk May 13 '20 at 09:16
0

As Selenium uses it would be tough to identify the <input> tags based on the texts Male or Female. As an alternative, to click() on the element related to the text Male you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following based Locator Strategies:

  • Male:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//td[@class='formtext' and contains(.,"Are you")]//following::td[1]/input"))).click()
    
  • Female:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//td[@class='formtext' and contains(.,"Are you")]//following::td[1]//following::input[2]"))).click()
    
  • 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