簡體   English   中英

無法選擇下拉值:jQuery,C#和Selenium

[英]Can't Select drop down value: jQuery, C#, and Selenium

我正在嘗試在下拉列表中選擇一個元素。 當我嘗試僅使用Selenium C#時,我遇到了Div錯誤,建議使用jQuery進行選擇.Div錯誤是應該選擇Element但應該是div。 我試過使用sendkeys選擇下拉列表,但是然后我得到了它不能集中在元素上的錯誤。

我目前有以下代碼,但無法使其運行:

using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;
using OpenQA.Selenium.Chrome;
using WebAuto;
using System.Drawing.Imaging;
using OpenQA.Selenium.Support.UI;
using Selenium.WebDriver.Extensions.JQuery;
using OpenQA.Selenium.Remote;

namespace WebAuto
{
    class AddTrade
    {
        [Test]
        public static void AddTrade1()
        {
            var driver = new ChromeDriver();
            driver.Navigate().GoToUrl("webaddress");
            var inputtext1 = driver.FindElement(OpenQA.Selenium.By.Id("lgLogin_txtUserId"));

            inputtext1.SendKeys("User");
            var inputpassword1 = driver.FindElement(OpenQA.Selenium.By.Id("lgLogin_txtPassword"));

            inputpassword1.SendKeys("Password");
            var inputbutton1 = driver.FindElement(OpenQA.Selenium.By.Id("btnLoginClient"));
            inputbutton1.Click();


            System.Threading.Thread.Sleep(3000);
            driver.FindElement(OpenQA.Selenium.By.Id("s2id_selTrader")).Click();

            $("#s2id_selTrader").val("Main Trader");

我該如何解決這個問題?

為了使用Selenium運行JavaScript,您需要使用驅動程序的IJavaScriptExecutor。 例如:

((IJavaScriptExecutor)driver).ExecuteScript("$('.toTop').remove();");

但是,我不知道這是從下拉菜單中選擇項目的最佳方法。 您是否嘗試過將元素強制轉換為SelectElement並使用該類中的方法之一:

   SelectElement select = new SelectElement(element);

   select.SelectByValue("123");

還有SelectByText和SelectByIndex。

您可以嘗試添加一個wait子句:

wait = new WebDriverWait(driver, new TimeSpan(0, 0, 10));
if (!driver.FindElement(By.CssSelector("selector")).Displayed)
{
    wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.CssSelector("selector")));
    driver.FindElement(By.CssSelector("selector")).Text; // There are other properties and methods if you need
}

如果我沒記錯的話,這些選擇不是真正的html select元素(因此,您不能將它們與Selenium的SelectElement一起使用),而是一些需要以不同方式交互的腳本div元素。

如果要重現實際用戶的體驗,則應嘗試這樣的操作

    public void SetDropdownValue(IWebElement dropdown, string value)
    {
        By valueXpath = By.XPath("//div[@id='select2-drop']//li[div[text()='" + value + "']]");
        dropdown.FindElement(By.XPath(".//b[@role='presentation']")).Click();

        new WebDriverWait(Driver, TimeSpan.FromSeconds(1)).Until(ExpectedConditions.ElementExists(valueXpath));
        Driver.FindElement(valueXpath).Click();
    }

請注意,根據條件的不同,該項目可能根本不可見(這將引發ElementNotVisibleException),因此您可能需要在單擊該元素之前嘗試使其可見。 如果是這種情況,您可以嘗試此處介紹的任何一種方法,並在檢查其存在之后添加它。

另外,檢查我提供的“ valueXpath”模型,看看它是否與頁面中的模型相等。 li可能在其中包含一個元素,因此您必須直接在其中找到具有所需選項文本的元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM