带有问题文本(标题)的单选按钮(选项)的 XPath

XPath for radio button (option) with question text (title)

我的 DOM 的相关部分如下所示:

<div class="questions" xpath="1">
<div class="question">
   <div class="section-name">General Knowledge</div>
   <div class="title" style="">Which of these cities is the capital of India?</div>
   <span class="description">Some description text</span>
   <div class="options">
      <div class="mui-radio"><label for="x7xvolm-116"><input id="x7xvolm-116" type="radio" value="116" style=""><span class="option-text">Mumbai</span></label></div>
      <div class="mui-radio"><label for="x7xvolm-117"><input id="x7xvolm-117" type="radio" value="117"><span class="option-text">Delhi</span></label></div>
      <div class="mui-radio"><label for="x7xvolm-118"><input id="x7xvolm-118" type="radio" value="118"><span class="option-text">Kolkata</span></label></div>
      <div class="mui-radio"><label for="x7xvolm-119"><input id="x7xvolm-119" type="radio" value="119"><span class="option-text">Chennai</span></label></div>
      <div class="mui-radio"><label for="x7xvolm-120"><input id="x7xvolm-120" type="radio" value="120"><span class="option-text">Bengaluru</span></label></div>
      <div class="mui-radio"><label for="x7xvolm-121"><input id="x7xvolm-121" type="radio" value="121"><span class="option-text">Nagpur</span></label></div>
   </div>
</div>

我需要想出一个有两个参数的 XPath,这将帮助我 select 来自 Selenium 代码的所需选项:

  1. 问题标题(Which of these cities is the capital of India?
  2. 选项标签(Delhi
.//\*[contains(text(),'Which of these cities is the capital of India?')]//following-sibling::div//\*[contains(text(),'Delhi')]

试试这个。希望这会奏效。

尝试使用以下 xpath 访问 radio 按钮。

//div[@class="title"][contains(.,"Which of these cities is the capital of India?")]/following-sibling::div[@class="options"]//span[contains(.,"Delhi")]/preceding-sibling::input[1]

//div[@class="title"][contains(.,"Which of these cities is the capital of India?")]/following-sibling::div[@class="options"]//span[contains(.,"Delhi")]/preceding-sibling::input

答案假定 Selenium Java Client Bindings

String question = "Which of these cities is the capital of India?"; 
String answer = "Delhi";                                            
driver.findElement(By.xpath("//div[text()= '" + question + "']" +   
        "/parent::*/div[@class='options']/descendant::*" +          
        "/span[text()='" + answer + "']")).click();                   

参考文献:

确定问题标题为 Which of these cities is the capital of India? 且选项标签为 Delhi 的所需选项,使用Selenium you can use the following :

//div[@class='title' and text()='Which of these cities is the capital of India?']//following::div[1]//label[span[@class='option-text' and text()='Delhi']]