Home > OS >  Selecting Radio Buttons only in single div
Selecting Radio Buttons only in single div

Time:10-16

Actually I'm doing tasks from http://demo.seleniumeasy.com/basic-radiobutton-demo.html - Group Radio Buttons Demo.

Is it possible to select buttons in a certain div? Because in my code length of my list generated by findelements() is 7 but I would like it to be a 5 (only buttons from Group Radio Buttons should be selected).

I know div is the same for all buttons but is there any other (better) selector that can be used here?

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
import time

PATH = r"C:/Users/*****/PycharmProjects/chromedriver.exe"

s = Service(PATH)
driver = webdriver.Chrome(service=s)

driver.get("http://demo.seleniumeasy.com/basic-radiobutton-demo.html")

#Single Radio Button Demo
button_radio_male = driver.find_element(by=By.XPATH,
                                        value="//label[normalize-space()='Male']//input[@name='optradio']")
button_radio_male.click()

button_get_checked_value = driver.find_element(by=By.ID, value="buttoncheck")
button_get_checked_value.click()


#Multiple Radio Button Demo
buttons = driver.find_elements(by=By.XPATH, value="//div[@class='panel-body']//input[@type='radio']")
print(len(buttons))

CodePudding user response:

Sure you can.
Instead of "//div[@class='panel-body']//input[@type='radio']" XPath locator you can use more precise locator

"//div[contains(@class,'panel') and(contains(.,'Group Radio Buttons Demo'))]//div[@class='panel-body']//input[@type='radio']"

This locator can even be simplified to this:

"//div[contains(@class,'panel') and(contains(.,'Group Radio Buttons Demo'))]//div[@class='panel-body']//input[@type='radio']"

Actually it can even be shortened to this:

"//div[contains(@class,'panel') and(contains(.,'Group'))]//div[@class='panel-body']//input[@type='radio']"

In the expression above we define the precise parent div element by it class name and text content of it child element.

CodePudding user response:

You can also use OR in the Xpath to locate only those 5 elements. Below is the Xpath for the those radio buttons from the Group Radio Buttons Demo.

//input[@name='gender' or @name='ageGroup']
  • Related