微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从类占位符文本框中获取文本

如何解决如何从类占位符文本框中获取文本

我一直在尝试从一个文本框中读取文本,这是一个类占位符,如下所示

更新:

 <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,但仍然无效。

这是我要阅读的文本框的示例

enter image description here

谢谢。

解决方法

你应该试试这个:

 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
,

发生了什么

  1. 您尝试通过 input

    获得 driver.FindElement(By.TagName("annotationHistoryDataTable")).Text;
  2. 问问自己:是否有标签名 annotationHistoryDataTable

那么如何选择这个input

  1. 它是一个 input 并且它有一个 aria-controls,在您的 xpath 中使用它:

    driver.FindElement(By.XPATH("//input[@aria-controls='annotationHistoryDataTable']"))
    
  2. 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()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。