如何使用Selenium Webdriver检查元素是否可见?

时间:2017-10-30 22:31:30

标签: selenium webdriver

有人可以就如何处理此问题提出任何建议吗?

来自HTML: -

<script type="text/javascript">
//<![CDATA[
var RequiredFieldValidator1 = document.all ? document.all["RequiredFieldValidator1"] : document.getElementById("RequiredFieldValidator1");
RequiredFieldValidator1.controltovalidate = "ddlAlligator";
RequiredFieldValidator1.focusOnError = "t";
RequiredFieldValidator1.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
RequiredFieldValidator1.initialvalue = "";
var ValidationSummary1 = document.all ? document.all["ValidationSummary1"] : document.getElementById("ValidationSummary1");
ValidationSummary1.headertext = "The form is missing required information.  Please review your answers.";
//]]>
</script>

我的C#代码:

private By NoFieldHeader = By.XPath("//label/div[text()='The form is missing required']");

    public bool IsNoField()
    {
        WebDriverWait wait = new WebDriverWait(_driver, TimeSpan.FromSeconds(3.00));
        wait.Until(ExpectedConditions.ElementIsVisible(NoFieldHeader ));
        return true;
    }

错误: -

  

WebDriver.Support.dll中出现“OpenQA.Selenium.WebDriverTimeoutException”类型的异常,但未在用户代码中处理   附加信息:3秒后超时

谢谢!

2 个答案:

答案 0 :(得分:0)

您的代码在编写时有效。你告诉它等待三秒钟,直到有问题的元素加载,如果没有超时。要么增加等待元素的等待时间,要么try another condition

答案 1 :(得分:0)

问题是你的XPath是text()=...。这意味着,从发布的HTML中提供的字符串是整个消息。您需要使用contains()或将text()=...更改为完整字符串,"The form is missing required information. Please review your answers."

如果有时候该元素不存在,则需要添加try-catch,抓住WebDriverTimeoutException,然后返回false