如何使用 Selenium 和 Java 来识别是否选择了带有伪元素 ::after 样式的单选按钮选项

How to identify if a radio button option styled with pseudo element ::after is selected or not using Selenium and Java

我很难确定是否选择了单选选项“否”或没有使用 Selenium Java。下面是网页单选选项的截图。

这是原始 HTML 代码。由于它缺少伪元素,我也附上了它的截图。

<div id="ButtonOptions" class="sample prop_group">
    <label class="vdl-radio">
       <input id="radio_K371FCY2UbrpgcP3RE6VC" type="radio" class="vdl-radio__input" tabindex="0" aria-disabled="false" value="true">
    <label for="radio_K371FCY2UbrpgcP3RE6VC">Yes</label>
    </label>
    <label class="vdl-radio">
       <input id="radio_4XLAugQMgEwzm3e2quk5y" type="radio" class="vdl-radio__input" tabindex="0" aria-disabled="false" value="false" checked="">
    <label for="radio_4XLAugQMgEwzm3e2quk5y">No</label>
    </label>
</div>

下面是 HTML 具有伪元素的代码的屏幕截图 ::after(下面突出显示)在未选择任何选项时动态加载。

我在下面创建了 Java 方法来执行 Java 我期望 return 整个 label for 标记的脚本。当前正在打印 null。但是,当我在 Chrome 浏览器控制台中执行下面使用的脚本时,它会识别整个标签标记,包括 ::before::after 伪元素。

        public String whichRadioOptionIsSelected(){
        String tag = "";      
        List<WebElement> radioOptions = findElementsByXpath(".//div[@id='ButtonOptions']/label");

        //Iterate thru both radio options and execute the JavaScript.

        for(int i = 1; i <= radioOptions.size(); i++) {
                String script = "return document.querySelector('div#ButtonOptions > label:nth-of-type("+i+") label', null);";
                JavascriptExecutor js = (JavascriptExecutor) driver;
                tag = (String) js.executeScript(script);
                System.out.println(tag);
            }        
        return tag;
    }
}

验证 with text as No is selected or not you can use the following based :

  • 使用前面:

    try {
        driver.findElement(By.xpath("//div[@id='ButtonOptions']//label[@class='vdl-radio']//label[text()='No']//preceding::input[@checked]"));
        System.out.println("No option is selected");
    }
    catch(NoSuchElementException e) {
        System.out.println("No option isn't selected");
    }
    
  • 使用 preceding-sibling:

    try {
        driver.findElement(By.xpath("//div[@id='ButtonOptions']//label[@class='vdl-radio']//label[text()='No']//preceding-sibling::input[@checked]"));
        System.out.println("No option is selected");
    }
    catch(NoSuchElementException e) {
        System.out.println("No option isn't selected");
    }
    

参考

您可以在以下位置找到有关伪元素的详细讨论: