c# - Selenium Xpath - 需要匹配元素的孙子
问题描述
我使用下面的 xpath 来获取大子元素的句柄:
Xpath:
driver.FindElement(By.XPath("//*[contains(@id,'contact.fieldControl-option-set-select')][2]"))
大教堂:
<div id="id-6789e999-a812-4ae0-8c39-a736a4ca4a19-19-contact.fieldControl-option-set-select" data-id="contact.fieldControl-option-set-select-container" role="presentation" class="dm bp hh ab z w flexbox">
<select id="id-6789e999-a812-4ae0-8c39-a736a4ca4a19-19-preferredcontactmethodcode-preferredcontactmethodcode.fieldControl-option-set-select" aria-label="Preferred Method of Contact" title="Preferred Method of Contact" data-id="preferredcontactmethodcode.fieldControl-option-set-select" describedbyelementid="" class="so sp sq ">
<option id="id-6789e999-a812-4ae0-8c39-a736a4ca4a19-19-contact.fieldControl-option-set-select" value="-1" class="sn qa ">---</option>
<option id="id-6789e999-a812-4ae0-8c39-a736a4ca4a19-19-contact.fieldControl-option-set-select" value="1" class="sn qa "">Any</option>
<option id="id-6789e999-a812-4ae0-8c39-a736a4ca4a19-19-contact.fieldControl-option-set-select" value="2" class="sn qa ">Email</option>
<option id="id-6789e999-a812-4ae0-8c39-a736a4ca4a19-19-contact.fieldControl-option-set-select" value="3" class="sn qa ">Phone</option>
<option id="id-6789e999-a812-4ae0-8c39-a736a4ca4a19-19-contact.fieldControl-option-set-select" value="4" class="sn qa ">Fax</option>
<option id="id-6789e999-a812-4ae0-8c39-a736a4ca4a19-19-contact.fieldControl-option-set-select" value="5" class="sn qa ">Letter</option>
</select>
</div>
注意:因为我的 xpath 匹配 div/select/options。我只是在这里寻找选项元素。
告诉我最有效和最简单的方法
解决方案
我认为您不应该使用比select
元素更深的 XPath。Selenium Wedriver 在“选择”->“选项”块上提供了一个抽象层,并为您提供了一种控制选项的好方法(参考:)SelectElement
:
using OpenQA.Selenium.Support.UI;
// select the drop down list
var education = driver.FindElement(By.CssSelector("select[title='Preferred Method of Contact']"));
// create select element object
var selectElement = new SelectElement(education);
然后您可以使用selectElement
按文本、值或索引选择选项。以及检索所有可用选项或所需选项。
推荐阅读
- php - 检索一个 json 代码并用一个框分隔它
- database - 移动节点之间的关系,避免重复
- javascript - 在 jasmine 测试中处理 Promise.all 中的拒绝
- protractor - 更新行的顺序后如何验证 Angular 网格的第一行?
- c - popen() 失败时如何解释 pclose() 状态?
- html - 覆盖父组件的 CSS 变量
- java - 尝试为 Java1.7 启用 TLSv1.2 时,TLS 握手失败。请启发我
- docker - 描述性管道和作为代理的 docker 工具
- android-studio - 我已经被困在“运行 Gradle 任务'assembleDebug'..”几个小时了
- python - Docker 容器以不明确的方式影响撰写环境中的其他人