使用Selenium的JavascriptExecutor操纵文本数值

huangapple go评论71阅读模式
英文:

Manipulating text values using Selenium JavascriptExecutor

问题

我正在尝试使用Selenium来更改字段的文本值。不幸的是,该字段不是<input>,而是一个带有伪类::before的div。

我需要能够在此字段中输入新的文本值,但迄今为止未能实现。

HTML片段:

<div class="stb-LazyChosenDropdown" tabindex="0">
   <div class="icon default" aria-hidden="true" style="display: none;"></div>
   <div class="tiles">
      <div class="input" contenteditable="true" placeholder="Enter values..." style="width: 383px; height: 17px;"></div>
        ::before
   </div>

我可以使用以下代码来打印已存在的值:

JavascriptExecutor js = (JavascriptExecutor)driver;
String content = (String) js.executeScript("return window.getComputedStyle(document.querySelector('div.stb-LazyChosenDropdown div.tiles div.input'),'::before').getPropertyValue('content')");
System.out.println(content);

这将打印出 Enter values...

但是如何将文本值更改为新的内容?

英文:

I am trying to use Selenium to change the text value of a field. Unfortunately, the field is not an <input> but a div with a pseudo class of ::before

I need to be able to input new text values into this field but have been unable to do so thus far.

The HTML snippet:

<div class="stb-LazyChosenDropdown" tabindex="0">
   <div class="icon default" aria-hidden="true" style="display: none;"></div>
   <div class="tiles">
      <div class="input" contenteditable="true" placeholder="Enter values..." style="width: 383px; height: 17px;"></div>
        ::before
   </div>

I can use the following to print the value already in place:

 JavascriptExecutor js = (JavascriptExecutor)driver;
 js.executeScript("return window.getComputedStyle(document.querySelector('div.stb-LazyChosenDropdown div.tiles div.input'),':before').getPropertyValue('content')")
 System.out.println(content);

Which prints Enter values...

But how to change the text value to something new?

答案1

得分: 0

找到元素使用任何定位策略并尝试添加`textContent`

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].textContent='Steerpike'", driver.findElement(By.cssSelector("div.input[placeholder^='Enter values']"));
英文:

Find the element using any locator strategies and Try to add the textContent

JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].textContent='Steerpike'", driver.findElement(By.cssSelector("div.input[placeholder^='Enter values']")))

huangapple
  • 本文由 发表于 2023年2月23日 22:14:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75546003.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定