首页 > 解决方案 > 如何处理网页 selenium c# 上的错误

问题描述

我已经编写了进入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();

标签: c#seleniumselenium-webdriver

解决方案


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

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());

推荐阅读