简体   繁体   English

检查 C# 中的元素是否为空

[英]check if element is empty in C#

I have this to enter data into an input field in a form:我有这个将数据输入表单中的输入字段:

Driver_.FindElement(By.XPath("//input[@aria-labelledby='i1']")).SendKeys("text to enter");

it works fine, but I need to check if the field is empty first I have tried:它工作正常,但我需要先检查该字段是否为空我试过:

string Result = Driver.FindElement(By.XPath("//input[@aria-labelledby='i1']")).Text;

but the var Result returns blank when the field contains text.但是当字段包含文本时,var Result返回空白。 I am trying to read the text in the field and act accordingly, with我正在尝试阅读该字段中的文本并采取相应的行动,

string Result = Driver.FindElement(By.XPath("//input[@aria-labelledby='i1']")).Text;

But returns blank.但返回空白。
.Tagname returns "input" .Tagname返回“输入”
.Enabled returns "True" .Enabled返回“真”
.Text returns "" .Text返回 ""

The HTML: HTML:

<input type="text" class="quantumWizTextinputPaperinputInput exportInput" jsname="YPqjbf" autocomplete="off" tabindex="0" aria-labelledby="i1" aria-describedby="i2 i3" dir="auto" data-initial-dir="auto" data-initial-value="this is text I put in the field" badinput="false">

Form input fields have a value property, which stores the text that was entered by the user.表单输入字段有一个value属性,它存储用户输入的文本。 You need to get the value property using Selenium:您需要使用 Selenium 获取 value 属性:

var input = Driver.FindElement(By.XPath("//input[@aria-labelledby='i1']"));

if (!string.IsNullOrEmpty(input.GetProperty("value")))
{
    input.SendKeys("text to enter");
}

Note that the value HTML attribute and value Document Object Model property are different things.请注意, value HTML 属性和value Document Object Model 属性是不同的东西。 The value HTML attribute usually retains the same text as when the page first loaded, but the value DOM property changes when the user enters or changes the text in the form field. value HTML 属性通常保留与第一次加载页面时相同的文本,但是当用户输入或更改表单字段中的文本时, value DOM 属性会发生变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM