[英]How do you grab the text for a label using Selenium
因此,我相信我能夠通過CSS選擇器或Xpath甚至是TagName來獲取元素,但是我無法獲取與之關聯的文本。
HTML如下所示:
<label for="AnswerText">This is the question text? </label>
在我的代碼中,我有:
static IWebDriver driver = new ChromeDriver(".");
static IWebElement securityQuestion = driver.FindElement(By.TagName("label"));
Console.WriteLine("question is ", securityQuestion.Text)
我想要做的是從標簽“這是問題文本?”中獲取此文本。 我這樣做是因為文本更改,並且根據答案,輸入將有所不同,因此我必須合並邏輯以獲取該文本並將其設置為與要匹配的變量相等。
我已經嘗試過.Text GetAttribute(“ value”),但是由於標簽沒有任何值以及不同的選擇器,因此無法正常工作。
static IWebDriver driver = new ChromeDriver(".");
static IWebElement securityQuestion = driver.FindElement(By.TagName("label"));
Console.WriteLine("question is ", securityQuestion.Text)
我沒有足夠的代表發表評論,但是您所擁有的應該可以工作。 讓我想知道您是否獲得了正確的元素。 當您嘗試打印文本時,異常/輸出是什么? 我假設頁面上有不止一個TagName為“ label”的元素。 我將嘗試找到一個更獨特的父元素,然后獲取具有您要查找的文本的子元素。
IWebElment elem = driver.FindElement(By.Id("ParentID")).FindElement(By.TagName("label"));
或者嘗試使用XPath ...也許您之前嘗試過的路徑不正確。 如果您提供更多有關HTML的信息,請嘗試提供幫助。
提取文本這是問題文本? 您必須為ElementIsVisible()
和GetAttribute("innerHTML")
誘導WebDriverWait ,並且可以使用以下定位策略之一 :
CssSelector
:
new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.CssSelector("label[for='AnswerText']"))).GetAttribute("innerHTML");;
XPath
:
new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementIsVisible(By.XPath("//label[for='AnswerText']"))).GetAttribute("innerHTML");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.