如何在 selenium WebDriver 中点击搜索文本结果

How to click on search text results in selenium WebDriver

如何在 selenium WebDriver 中单击搜索文本框的特定文本。在我的例子中,搜索文本框是“学校”。

我在文本框“学校”中发送密钥“RGSchool1”,然后我想在“RGScool”作为结果显示在文本框下方时单击它。

我尝试了以下所有方法,方法是抛出“org.openqa.selenium.NoSuchElementException”

  1. 输入文本并跳出
  2. 输入文本并发送回车键
  3. 绝对路径-/html1/body1/div[7]/ul1/li1/div1/span1
  4. 相对路径 - //span[@class='select2-match']

HTML正文:

<div class="select2-result-label" style="" xpath="1">
<span class="select2-match">RGSchoo</span>
l1 [rgschool1]</div>

代码: //查找元素

@FindBy(id = "s2id_User_OrgId")
public WebElement clickJurisdiction;

@FindBy(xpath = "/html[1]/body[1]/div[6]/div[1]/input[1]")
public WebElement keyInJurisdiction;

@FindBy(xpath = "//div[@id='s2id_User_OrgUnitId']//a[@class='select2-        choice']")
public WebElement clickSchool;

@FindBy(xpath = "/html[1]/body[1]/div[7]/div[1]/input[1]")
public WebElement keyInSchool;

@FindBy(xpath = "/html[1]/body[1]/div[7]/ul[1]/li[1]/div[1]")
public WebElement schoolSearchResult2;

调用方式:

public void enterNewUserData() {

    SeleniumTestHelper.enterText(firstName, Config.getProperty("FirstName"));
    SeleniumTestHelper.enterText(middleName, Config.getProperty("MiddleName"));
    SeleniumTestHelper.enterText(lastName, Config.getProperty("LastName"));
    SeleniumTestHelper.enterText(preferredName, Config.getProperty("PreferredName"));
    
    SeleniumTestHelper.clickOnButton(clickJurisdiction);
    SeleniumTestHelper.enterText(keyInJurisdiction, Config.getProperty("Jurisdiction"));
    SeleniumTestHelper.enter(keyInJurisdiction);

    SeleniumTestHelper.clickOnButton(clickSchool);
    SeleniumTestHelper.enterText(keyInSchool, Config.getProperty("School"));
    SeleniumTestHelper.clickOnButton(schoolSearchResult2); // It fails here

请帮我找到解决办法。我对这种情况很陌生。

请看下面的截图。

输入数据前的截图:

Screenshot after entering data

要定位文本为 RGSchool1 的元素,您可以使用以下 :

  • 使用 cssSelector:

    @FindBy(cssSelector = "ul.select2-results div.select2-result-label > span.select2-match")
    public WebElement schoolSearchResult2;
    
  • 使用 xpath:

    @FindBy(xpath = "//ul[@class='select2-results']//div[@class='select2-result-label']/span[@class='select2-match']")
    public WebElement schoolSearchResult2;