【问题标题】:remove/change a specific element class attribute value using selenium使用 selenium 删除/更改特定元素类属性值
【发布时间】:2019-11-05 04:56:13
【问题描述】:

我有一个基于similar question 的问题,该问题有答案但不适合我。我有一个没有像 class="vote-link up" 这样设置的元素,它可以很容易地使类更改其属性,因为这只是一个词,我的词与它不相似。

HTML 代码看起来像这样<textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px; height: 40px; border: 1px solid rgb(193, 193, 193); margin: 10px 25px; padding: 0px; resize: none; display: none;"></textarea>

我想删除 HTML 代码的最后两个属性 display: none;。或者将其更改为 display: shown; 执行我显示的选项之一会得到与我想要的相同的结果,我只是不知道该怎么做。

也就是说,这就是我想要的,将 HTML 更改为 <textarea id="g-recaptcha-response" name="g-recaptcha-response" class="g-recaptcha-response" style="width: 250px; height: 40px; border: 1px solid rgb(193, 193, 193); margin: 10px 25px; padding: 0px; resize: none;"></textarea>

【问题讨论】:

    标签: java html selenium selenium-webdriver css-selectors


    【解决方案1】:

    为了澄清,display 不是属性它是style 属性的属性之一。这是reference了解更多信息。

    以下是处理您的场景的 2 个选项。

    选项一:更新样式显示属性值为block

    JavascriptExecutor js = (JavascriptExecutor)driver;
    WebElement ele = driver.findElement(By.id("g-recaptcha-response"));
    System.out.println("Before updating the property:" + ele.getAttribute("style"));
    js.executeScript("arguments[0].style.display = 'block';",ele);
    System.out.println("After updating the property:" + ele.getAttribute("style"));
    

    选项2:移除样式>显示属性

    JavascriptExecutor js = (JavascriptExecutor)driver;
    ele = driver.findElement(By.id("g-recaptcha-response"));
    js.executeScript("arguments[0].style.removeProperty('display')",ele);
    System.out.println("After deleting the property:" + ele.getAttribute("style"));
    

    【讨论】:

    • 查看OP提供的第二个HTML,他已经能够删除属性display: none;
    • OP 想要那个输出,而不是他能够删除该属性。根据我的理解,OP 询问如何去做。
    • 正如@supputuri 所说,我在问怎么做
    猜你喜欢
    • 2017-01-18
    • 2021-02-12
    • 2018-04-19
    • 2019-04-21
    • 2021-06-21
    • 2013-01-25
    • 2016-01-14
    • 2015-03-03
    • 2017-10-04
    相关资源
    最近更新 更多