如何在Selenium和C#上的相同测试用例中的多个页面上使用click事件

时间:2018-05-09 03:58:21

标签: c# .net selenium selenium-webdriver

如何在Selenium和C#

上的相同测试用例中的多个页面上使用click事件

例如:

转到Google主页。

搜索生成的测试

点击“搜索”按钮, 用户被重定向到搜索结果页面,但是当我尝试选择任何显示错误的链接时。

public void opengoogle()
    {
        ChromeOptions option = new ChromeOptions();
        option.AddArgument("--headless");
        ChromeDriver wd = new ChromeDriver(option);
        try
        {

            wd.Navigate().GoToUrl("https://www.google.co.in/");
            Thread.Sleep(2000);
            wd.FindElement(By.CssSelector("#lst-ib")).Click();
            Thread.Sleep(2000);
            wd.FindElement(By.CssSelector("#lst-ib")).Click();
            wd.FindElement(By.CssSelector("#lst-ib")).Clear();
            wd.FindElement(By.CssSelector("#lst-ib")).SendKeys("Test");
            wd.FindElement(By.CssSelector("#lst-ib")).Submit();
        }
        finally {  }

2 个答案:

答案 0 :(得分:0)

您可以试用代码

ChromeOptions option = new ChromeOptions();
option.AddArgument("--headless");
ChromeDriver wd = new ChromeDriver(option);
wd.Navigate().GoToUrl("https://www.google.co.in/");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMinutes(1));  
wait.Until(ExpectedConditions.ElementToBeClickable(By.Name("q")));  
wd.FindElement(By.Name("q")).SendKeys("Test"+Keys.RETURN);  
wait.Until(ExpectedConditions.VisibilityOfElementLocated(By.CssSelector("a[href='http://www.speedtest.net/']")));  
driver.FindElement(By.CssSelector("a[href='http://www.speedtest.net/']")).Click();  

P.S: 虽然我试图将java代码转换为C#,但我对C#并不擅长。希望这对你有所帮助。
2.这将始终打开speedtest.net网站。如果你想要别的东西,你可以通过替换我写过的cssSelector来获得它。

答案 1 :(得分:0)

public void TestMethod1()
    {      
        ChromeOptions option = new ChromeOptions();
        option.AddArgument("--headless");
        ChromeDriver webDriver = new ChromeDriver(option);
        try
        {
            webDriver.Navigate().GoToUrl("https://www.google.lk/");
            WebDriverWait wait = new WebDriverWait(webDriver, new TimeSpan(0, 0, 0, 30));
            IWebElement searchTextField= wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("lst-ib")));
            searchTextField.SendKeys("Test");
            IWebElement searchButton = wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector(".lsb")));
            searchButton.Click();
            wait.Until(ExpectedConditions.TitleContains("Test"));
            IWebElement searchResultLink= wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("a[href='http://www.speedtest.net/']")));
            searchResultLink.Click();
        }
        finally { }
    }

您可以尝试以上代码。 它解释了以下过程。

  • 首先转到Google搜索页面。
  • 将“测试”插入搜索文本字段。
  • 然后点击Google搜索按钮。
  • 导航至搜索结果页面后,单击“www.speedtest.net”链接。