首页 > 解决方案 > 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。我只是在这里寻找选项元素。

告诉我最有效和最简单的方法

标签: c#selenium-webdriverxpath

解决方案


我认为您不应该使用比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按文本、值或索引选择选项。以及检索所有可用选项或所需选项。


推荐阅读