Reputation: 147
I'm trying to use python and selenium to select a specific radio button out of a few that live within a web page. Luckily, the radio button that I want to select does have specific text associated, which should make it easier for me to select. Unfortunately, I'm missing something since all attempts have errored out. Below is the HTML code, what i've tried, and what i'm trying to achieve.
HTML
<div data-a-input-name="slotsRadioGroup" class="a-radio a-radio-fancy slotButtonRadio"><label><input type="radio" name="slotsRadioGroup" value="" autocomplete="off"><i class="a-icon a-icon-radio"></i><span class="a-label a-radio-label">
<span class="slotRadioLabel">
5PM - 7PM
</span>
<div class="a-row">
<span class="a-size-small slot-button-micro-copy preselected-visible">
Soonest available time with all items.
</span>
</div>
</span></label></div>
</div></div>
The radio button I need to select will always have the text "Soonest available..." present.
What I've tried
I've tried different variations of xpath code to attempt to select this based on the text. My last attempt was:
driver.find_element_by_xpath("//input[@type='radio']and following-sibling::span[contains(., 'Soonest available')").click()
Which results in the following error:
SyntaxError: Failed to execute 'evaluate' on 'Document': The string '//input[@type='radio']and following-sibling::span[contains(., 'Soonest available')' is not a valid XPath expression.
Expected Result What I want is to be able to select the specific radio button based on the above text being present.
Upvotes: 1
Views: 1207
Reputation: 33384
To Select Radio button based on text Induce WebDriverWait
and wait for element_to_be_clickable
() and following xpath
options.
XPATH 1:
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//label[.//span[contains(.,'Soonest available time with all items')]]/input[@name='slotsRadioGroup']"))).click()
XPATH 2:
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,"//span[contains(.,'Soonest available time with all items')]/preceding-sibling::input[1]"))).click()
If Web driver click not work then you can try javascripts
executor to click the same.
radiobtn=WebDriverWait(driver,10).until(EC.visibility_of_element_located((By.XPATH,"//label[.//span[contains(.,'Soonest available time with all items')]]/input[@name='slotsRadioGroup']")))
driver.execute_script("arguments[0].click();", radiobtn)
Note:- You need to import following libraries.
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
Upvotes: 1
Reputation: 608
Try this:
for i in driver.find_elements_by_tag_name("span"):
if "Soonest available" in i.text:
result = i
break
Upvotes: 0