簡體   English   中英

如何使用 Python 和 Selenium 更改元素的 class 屬性的值

[英]How to change the value of the class attribute of an element using Python and Selenium

我想更改 class 名稱,但它對我不起作用。

<div class="vcp-controls-panel vcp-playing hide">

全路徑:

/html/body/div[1]/div/div/div/div[2]/div/div/div[1]/div[1]/div[1]/div/div[1]/div[3]/div/div[1]/div/div[1]/div[9]/div[4]

我想將vcp-playing hide更改為vcp-playing show但它不起作用

selects = driver.find_element_by_class_name("vcp-playing hide")
    for select in selects:
        driver.execute_script("arguments[0].setAttribute('class', 'vcp-playing show')", select)

由於現有元素已經設置了classname屬性:

<div class="vcp-controls-panel vcp-playing hide">

您可以通過removeAttribute()刪除現有屬性,使用setAttribute() ) 設置新屬性,如下所示:

selects = driver.find_elements(By.CSS_SELECTOR, "div.vcp-controls-panel.vcp-playing.hide")
for select in selects:
    driver.execute_script("arguments[0].removeAttribute('class')", select);
    driver.execute_script("arguments[0].setAttribute('class','vcp-controls-panel vcp-playing show')", select)

注意:您必須添加以下導入:

from selenium.webdriver.common.by import By

在 javascript 中完成它怎么樣

driver.execute_script("""
    selects = document.querySelectorAll('.vcp-playing.hide')
    selects.forEach(e => e.setAttribute('class', 'vcp-playing show'))
""")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM