如何使用 Python 和 Selenium 更改元素的类属性值

发布于 2025-01-13 10:13:56 字数 564 浏览 2 评论 0原文

我想更改班级名称,但这对我不起作用。

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

FullXpath:

/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)

I want to change the class name, but it doesn't work for me.

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

FullXpath:

/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]

I want to change vcp-playing hide to vcp-playing show but it doesn't work

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

铜锣湾横着走 2025-01-20 10:13:56

由于现有元素已经设置了 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

As the existing element already have the classname attribute set:

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

You can remove the existing attributes through removeAttribute() set the new attributes using setAttribute() as follows:

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)

Note : You have to add the following imports :

from selenium.webdriver.common.by import By
爱要勇敢去追 2025-01-20 10:13:56

完全用 javascript 来做怎么样?

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

how about do it completely in javascript

driver.execute_script("""
    selects = document.querySelectorAll('.vcp-playing.hide')
    selects.forEach(e => e.setAttribute('class', 'vcp-playing show'))
""")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文