Как прочитать текст с выбранной радиокнопки и как выбрать другую радиокнопку? - PullRequest
0 голосов
/ 03 июля 2018

Я хочу прочитать выбранный текст переключателя и хочу выбрать другое поле переключателя, поэтому я читаю текст всех 3 переключателей и перехожу к строкам и пытаюсь выбрать переключатель, который не выбран, но использую, если условие не в состоянии сделать это, пожалуйста, помогите мне установить флажок.

Это HTML-код

<ul class="custom-ul">
    <li class="custom-li custom-radio m-subscriptions-padding receive-VIP1">
        <input name="email-preferences" id="receive-VIP" type="radio" value="receive-VIP1">
        <input name="_D:email-preferences" type="hidden" value=" ">                       <label for="receive-VIP" class="custom-radio-label">
             <span class="label-alt-text">Receive special offers via email</span>
        </label>
    </li>
    <li class="custom-li custom-radio m-subscriptions-padding receive-fewer1">
        <input name="email-preferences" checked="checked" id="receive-fewer" type="radio" value="receive-fewer1" class="radio-checked">
        <input name="_D:email-preferences" type="hidden" value=" ">
        <label for="receive-fewer" class="custom-radio-label">
             <span class="label-alt-text">Receive fewer emails. We won't email you more than one time per week.</span>
        </label>
    </li>
    <li class="custom-li custom-radio m-subscriptions-padding receive-no-emails">
        <input name="email-preferences" id="receive-no-emails" type="radio" value="receive-no-emails">
        <input name="_D:email-preferences" type="hidden" value=" ">
        <label for="receive-no-emails" class="custom-radio-label">
             <span class="label-alt-text"> Unsubscribe: we will remove you from all testdevv promotional emails.</span>
        </label>
        </li>
</ul>

Ответы [ 3 ]

0 голосов
/ 03 июля 2018

Вы можете найти выбранный текст опции и список всех доступных опций, как показано ниже.

Пожалуйста, используйте приведенную ниже логику в вашем коде

Код:

    //If none of the option is selected, then exception will be thrown and to avoid this we can use findElements method
    List<WebElement> radioButtonSelectedList=driver.findElements(By.xpath("//*[@class='radio-checked']//parent::*//span"));
    String selectedValue="";
    ArrayList<String> optionsList = new ArrayList<String>();

    if(radioButtonSelectedList.size()!=0){
        //If the button is selected, then we can get the selected option text
        selectedValue=radioButtonSelectedList.get(0).getText();

        //To get all the available Options
        List<WebElement> optionsElement=driver.findElements(By.xpath("//ul[@class='custom-ul']//span"));

        for(WebElement element: optionsElement){
            optionsElement.add(element);
        }

    }
    else{
        System.out.println("None of the option is selected");
    }

    System.out.println("Available Options :"+optionsList);
    System.out.println("Selected Option :"+selectedValue);
0 голосов
/ 10 июля 2018

Вы можете попробовать следующее решение:

    //this is row with radiobutton and text
    private By customRadioElement = By.xpath("//li[contains(@class, 'custom-radio')]");
    //this is all radiobuttons
    private By radiobutton = By.xpath("./input[@name='email-preferences']");
    //this is all labels for radiobuttons
    private By radiobuttonLabel = By.xpath("./label/span");

    public void selectRadiobutton(String labelText) {
        List<WebElement> tempList = driver.findElements(customRadioElement);
        for (WebElement element : tempList) {
            //webElement can search for elements, and if xpath locator starts with "." element will search for element from his children
            if (labelText.equals(element.findElement(radiobuttonLabel).getText())) {
                element.findElement(radiobutton).click();
            }
        }
    }

    public String getSelectedRadiobuttonLabelText() {
        List<WebElement> tempList = driver.findElements(customRadioElement);
        for (WebElement element : tempList) {
            //webElement can search for elements, and if xpath locator starts with "." element will search for element from his children
            if (element.findElement(radiobutton).isSelected()) {
                return element.findElement(radiobuttonLabel).getText();
            }
        }
        return "";
    }
0 голосов
/ 03 июля 2018

Попробуйте -

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class A {

    public static void main(String[] args) {
        WebDriver driver = new ChromeDriver();
        driver.get("url here");
        List<WebElement> radioButtons = driver.findElements(By.name("email-preferences"));
        for (int i = 0; i < radioButtons.size(); i++) {
            if (driver.findElement(By.name("email-preferences")).isSelected()) {
                System.out.println(radioButtons.get(i).getText());
                break;
            }
        }
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...