Program Club

Selenium WebDriver C #을 사용하여 드롭 다운에서 옵션을 선택하는 방법은 무엇입니까?

proclub 2020. 10. 13. 19:35
반응형

Selenium WebDriver C #을 사용하여 드롭 다운에서 옵션을 선택하는 방법은 무엇입니까?


웹 테스트에서 옵션을 선택하려고했습니다. 예는 여기에서 찾을 수 있습니다 : http://www.tizag.com/phpT/examples/formex.php

옵션 부분을 선택하는 것을 제외하고는 모든 것이 잘 작동합니다. 값 또는 레이블로 옵션을 선택하는 방법은 무엇입니까?

내 코드 :

using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using System.Threading;
using System.Diagnostics;
using System.Runtime.InteropServices;

class GoogleSuggest
{
    static void Main()
    {
        IWebDriver driver = new FirefoxDriver();

        //Notice navigation is slightly different than the Java version
        //This is because 'get' is a keyword in C#
        driver.Navigate().GoToUrl("http://www.tizag.com/phpT/examples/formex.php");
        IWebElement query = driver.FindElement(By.Name("Fname"));
        query.SendKeys("John");
        driver.FindElement(By.Name("Lname")).SendKeys("Doe");
        driver.FindElement(By.XPath("//input[@name='gender' and @value='Male']")).Click();
        driver.FindElement(By.XPath("//input[@name='food[]' and @value='Chicken']")).Click();
        driver.FindElement(By.Name("quote")).Clear();
        driver.FindElement(By.Name("quote")).SendKeys("Be Present!");
        driver.FindElement(By.Name("education")).SendKeys(Keys.Down + Keys.Enter); // working but that's not what i was looking for
        // driver.FindElement(By.XPath("//option[@value='HighSchool']")).Click(); not working
        //  driver.FindElement(By.XPath("/html/body/table[2]/tbody/tr/td[2]/table/tbody/tr/td/div[5]/form/select/option[2]")).Click(); not working
        // driver.FindElement(By.XPath("id('examp')/x:form/x:select[1]/x:option[2]")).Click(); not working

        }
}

드롭 다운 목록에서 선택 요소 개체를 만들어야합니다.

 using OpenQA.Selenium.Support.UI;

 // select the drop down list
 var education = driver.FindElement(By.Name("education"));
 //create select element object 
 var selectElement = new SelectElement(education);

 //select by value
 selectElement.SelectByValue("Jr.High"); 
 // select by text
 selectElement.SelectByText("HighSchool");

여기에 더 많은 정보


다른 방법은 다음과 같습니다.

driver.FindElement(By.XPath(".//*[@id='examp']/form/select[1]/option[3]")).Click();

선택하려는 요소의 수로 x를 변경하여 option [x]에서 인덱스를 변경할 수 있습니다.

그것이 최선의 방법인지는 모르겠지만 도움이 되었기를 바랍니다.


이것에 포인트를 추가합니다. C # 프로젝트에 Selenium.NET 바인딩을 설치 한 후 OpenQA.Selenium.Support.UI 네임 스페이스를 사용할 수 없다는 문제가 발생했습니다. 나중에 다음 명령을 실행하여 최신 버전의 Selenium WebDriver 지원 클래스를 쉽게 설치할 수 있음을 알게되었습니다.

Install-Package Selenium.Support

NuGet 패키지 관리자 콘솔에서 또는 NuGet 관리자에서 Selenium.Support를 설치합니다.


텍스트를 통해 옵션을 선택하려면;

(new SelectElement(driver.FindElement(By.XPath(""))).SelectByText("");

값을 통해 옵션을 선택하려면 :

 (new SelectElement(driver.FindElement(By.XPath(""))).SelectByValue("");

값을 전달하고 키를 입력하기 만하면됩니다.

driver.FindElement(By.Name("education")).SendKeys("Jr.High"+Keys.Enter);

이것이 나를 위해 작동하는 방식입니다 (ID로 제어 및 텍스트로 옵션 선택).

protected void clickOptionInList(string listControlId, string optionText)
{
     driver.FindElement(By.XPath("//select[@id='"+ listControlId + "']/option[contains(.,'"+ optionText +"')]")).Click();
}

사용하다:

clickOptionInList("ctl00_ContentPlaceHolder_lbxAllRoles", "Tester");

드롭 다운에서 항목을 선택하기위한 Selenium WebDriver C # 코드 :

IWebElement EducationDropDownElement = driver.FindElement(By.Name("education"));
SelectElement SelectAnEducation = new SelectElement(EducationDropDownElement);

드롭 다운 항목을 선택하는 세 가지 방법이 있습니다. i) 텍스트로 선택 ii) 인덱스로 선택 iii) 값으로 선택

텍스트로 선택 :

SelectAnEducation.SelectByText("College");//There are 3 items - Jr.High, HighSchool, College

색인으로 선택 :

SelectAnEducation.SelectByIndex(2);//Index starts from 0. so, 0 = Jr.High 1 = HighSchool 2 = College

값으로 선택 :

SelectAnEducation.SelectByValue("College");//There are 3 values - Jr.High, HighSchool, College

If you are looking for just any selection from the drop-down box, I also find "select by index" method very useful.

if (IsElementPresent(By.XPath("//select[@id='Q43_0']")))
{
    new SelectElement(driver.FindElement(By.Id("Q43_0")))**.SelectByIndex(1);** // This is selecting first value of the drop-down list
    WaitForAjax();
    Thread.Sleep(3000);
}
else
{
     Console.WriteLine("Your comment here);
}

 var select = new SelectElement(elementX);
 select.MoveToElement(elementX).Build().Perform();

  var click = (
       from sel in select
       let value = "College"
       select value
       );

IWebElement element = _browserInstance.Driver.FindElement(By.XPath("//Select"));
IList<IWebElement> AllDropDownList = element.FindElements(By.XPath("//option"));
int DpListCount = AllDropDownList.Count;
for (int i = 0; i < DpListCount; i++)
{
    if (AllDropDownList[i].Text == "nnnnnnnnnnn")
    {
        AllDropDownList[i].Click();
        _browserInstance.ScreenCapture("nnnnnnnnnnnnnnnnnnnnnn");
    }
}

참고URL : https://stackoverflow.com/questions/5278281/how-to-select-an-option-from-drop-down-using-selenium-webdriver-c

반응형