下面HTML标记的xpath/Css选择器是什么,如何使用Seleniumxpath选择特定的单选按钮


  1. 下面HTML标记的xpath/Css选择器是什么,我的问题是如何单击Bike的单选按钮
  2. 让我们假设下面是动态单选按钮,我们有100个数字单选按钮,这里我们无法预测单选按钮的索引号

HTML:

<table> 
<tbody>
<tr><td class="textAlignCenter" id="clientDocTypeSelection"><input class="marginL10" name="clientRadio" type="radio"></td><td id="clientDocTypeDescription"> Bike </td></tr>
<tr><td class="textAlignCenter" id="clientDocTypeSelection"><input class="marginL10" name="clientRadio" type="radio"></td><td id="clientDocTypeDescription"> Car </td></tr>
</tbody> 
</table>

用您要查找的文本查找td,如下所示:

tds = driver.find_elements_by_xpath("//td[@class='textAlignCenter']")
for td in tds:
if td.text == 'Bike':
radio_input = td.find_element_by_xpath(".//input[@type='radio']")

对于文本为Bike的单选按钮上的click(),您可以使用以下基于xpath的定位器策略之一:

  • 使用Javanormalize-space():

    driver.findElement(By.xpath("//td[@id='clientDocTypeDescription' and normalize-space()='Bike']//preceding::td[1]/input")).click();
    
  • 使用Javacontains():

    driver.findElement(By.xpath("//td[contains(., 'Bike')]//preceding::td[1]/input")).click();
    

理想情况下,对于元素上的click(),您需要诱导WebDriverWait等待elementToBeClickable(),并且您可以使用以下定位器策略之一:

  • 使用Javanormalize-space():

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//td[@id='clientDocTypeDescription' and normalize-space()='Bike']//preceding::td[1]/input"))).click();
    
  • 使用Javacontains():

    new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//td[contains(., 'Bike')]//preceding::td[1]/input"))).click();
    

最新更新