Selenium(使用python)如何修改css sty元素

2024-03-28 13:35:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用selenium将元素的CSS样式(例如:从"visibility: hidden;"更改为"visibility: visible;")。(通过selenium+python的任何其他方法都会被优雅地接受)。

我的代码:

driver = webdriver.Firefox()
driver.get("http://www.example.com")

elem = driver.find_element_by_id('copy_link')

elem.execute_script(  area of my problem )

我需要做什么才能玩网页的CSS?


Tags: 方法代码http元素getdriverselenium样式
3条回答

这是我使用文档样式表找到的解决方案。 这种方法很好,因为您还可以添加伪类样式。

script = 'document.styleSheets[0].insertRule("button:focus {background-color: red !important;}", 0 )' 
driver.execute_script(script)

execute_script()中的字符串是要运行的JS代码(docs)。

如果您使用jQuery,它可以是

driver.execute_script("$('#copy_link').css('visibility', 'visible');")

下面是一个不使用任何jQuery的示例。它将隐藏谷歌的标志。

from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.google.com")
driver.execute_script("document.getElementById('lga').style.display = 'none';")

例如,通过将.style.display设置为"block",可以使用相同的思想来显示隐藏元素。

相关问题 更多 >