问题描述
我一直在尝试从一个文本框中读取文本,这是一个类占位符,如下所示
更新:
<div id="annotationHistoryDataTable_filter" class="dataTables_filter">
<label>Search:<input type="search" class="" placeholder="" aria-
controls="annotationHistoryDataTable">
</label></div>
我正在使用下面的代码来获取文本,但我得到了一个空值。这通常会获取所有文本,但不适用于此类文本框。
var theseElements = driver.FindElement(By.TagName("annotationHistoryDataTable")).Text;
也尝试过 By.LinkText,但仍然无效。
这是我要阅读的文本框的示例
谢谢。
解决方法
你应该试试这个:
var theseElements = driver.FindElement(By.TagName("annotationHistoryDataTable")).get_attribute("innerText");
,
您的定位器看起来不正确:
var theseElements = driver.FindElement(By.TagName("annotationHistoryDataTable")).Text;
没有具有该名称的标签,请在定位器下方使用
var theseElements = driver.FindElement(By.XPATH("//input[@aria-controls=\"annotationHistoryDataTable\" and @type = \"search\"]"));
现在试试;
theseElements.text
theseElements.getAttribute('value')
更新:
因为元素在 iframe 内,所以你需要先切换到它
driver.SwitchTo().Frame(driver.FindElement(By.XPATH("iframexpath")));
var theseElements = driver.FindElement(By.XPATH("//input[@aria-controls=\"annotationHistoryDataTable\" and @type = \"search\"]"));
theseElements.getAttribute('value') //print this
如果你想在这之后与iframe之外的元素进行交互,那么你必须切换到iframe之外;
driver.SwitchTo().DefaultContent(); // just add this line after you are done with interacting with iframe elements
,
发生了什么
-
您尝试通过
获得input
driver.FindElement(By.TagName("annotationHistoryDataTable")).Text;
-
问问自己:是否有标签名
annotationHistoryDataTable
?
那么如何选择这个input
?
-
它是一个
input
并且它有一个aria-controls
,在您的xpath
中使用它:driver.FindElement(By.XPATH("//input[@aria-controls='annotationHistoryDataTable']"))
-
text
不存储在<input>
之间,它存储在value
属性中,因此您应该像这样访问它:.GetAttribute("value")
示例
它是在 python 中的,但应该告诉你我的意思。
from selenium import webdriver
browser = webdriver.Chrome('C:\Program Files\ChromeDriver\chromedriver.exe')
html_content = """
<label>
Search:<input type="search" class="" placeholder="" aria-controls="annotationHistoryDataTable">
</label>
"""
browser.get("data:text/html;charset=utf-8,{html_content}".format(html_content=html_content))
browser.find_element_by_xpath("//input[@aria-controls='annotationHistoryDataTable']").get_attribute("value")
browser.close()