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

时间:2019-06-12 10:06:05

标签: selenium-webdriver xpath webdriver xpath-1.0

这是我的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,这将帮助我从Selenium代码中选择所需的选项:

  1. 问题标题(Which of these cities is the capital of India?
  2. 选项标签(Delhi

4 个答案:

答案 0 :(得分:1)

.//\*[contains(text(),'Which of these cities is the capital of India?')]//following-sibling::div//\*[contains(text(),'Delhi')]

尝试一下。希望这会起作用。

答案 1 :(得分:1)

尝试以下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]

OR

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

答案 2 :(得分:1)

答案假定为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();                   

参考文献:

答案 3 :(得分:1)

要使用Selenium来将“问题标题”标识为这些城市中的哪个城市是印度的首都?,并将选项标签标识为 Delhi ,请使用以下

//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']]