如何处理网页硒C#上的错误

时间:2018-07-12 10:52:03

标签: c# selenium selenium-webdriver

我已经写了https://energy.gocompare.com/gas-electricity上的代码。

我想在代码中引入另一个参数。因此,当我进入网页并在不输入任何数据的情况下单击“继续”按钮时,在“请提供您的邮政编码,因为不同地区的燃油价格不同。”页面上出现验证错误。

我如何在代码中引入检查,以验证显示的消息是否正确。我试图找到一个XPath,但是我不确定这是正确的方法

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Interactions;
using System.Threading;

namespace Exercise1
{
    class RunPath
    {

            static void Main()
            {

                IWebDriver webDriver = new ChromeDriver();
                webDriver.Navigate().GoToUrl("https://energy.gocompare.com/gas-electricity");
                webDriver.Manage().Window.Maximize();

webDriver.FindElement(By.XPath(".//button[@type = 'submit']")).Click();

3 个答案:

答案 0 :(得分:0)

我尝试了这个cssSelector

     div[class$='validation-error']

正在寻找获取错误消息。

在Java + TestNG中,通常会进行断言

  Assert.assertEquals(driver.findElement(By.cssSelector("div[class$='validation-error']")).getText().trim(), "Please provide your postcode, as different regions have different fuel prices.");

答案 1 :(得分:0)

您需要等待验证错误元素:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Interactions;
using System.Threading;

namespace Exercise1
{
    class RunPath
    {
            static void Main()
            {
                IWebDriver webDriver = new ChromeDriver();
                webDriver.Navigate().GoToUrl("https://energy.gocompare.com/gas-electricity");
                webDriver.Manage().Window.Maximize();

                webDriver.FindElement(By.XPath(".//button[@type = 'submit']")).Click();

                WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(10));
                IWebElement error = wait.Until(ExpectedConditions.ElementExists(By.XPath("//div[contains(@class, 'validation-error')]")));
                Assert.AreEqual("Please provide your postcode, as different regions have different fuel prices.", validationError.Text.TextTrim());
            }
    }           
}   

答案 2 :(得分:0)

点击继续按钮后,您可以尝试以下代码:

WebDriverWait wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(10));
IWebElement error = wait.Until(ExpectedConditions.ElementExists(By.XPath("//div[contains(@class, 'validation-error')]")));
Assert.AreEqual("Please provide your postcode, as different regions have different fuel prices.", error.Text.TextTrim());