Python Selenium - 高亮元素不做任何事情

标签 python selenium selenium-chromedriver highlight

我正在尝试使用 python selenium 突出显示以下网页上的元素。我正在使用此处发布的解决方案:How can I highlight element on a webpage using Selenium-Python?但它根本不会产生任何效果。我没有收到任何错误消息,只是没有突出显示我选择的元素。 有人遇到过同样的问题吗? 这是我的代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time

chromeOptions = webdriver.ChromeOptions()
driver = webdriver.Chrome()
driver.maximize_window()
url = "https://learn.letskodeit.com/p/practice"
driver.get(url)

def highlight(element):
    """Highlights (blinks) a Selenium Webdriver element"""
    driver = element._parent
    def apply_style(s):
        driver.execute_script("arguments[0].setAttribute('style', arguments[1]);",
                              element, s)
    original_style = element.get_attribute('style')
    apply_style("border: 2px solid red;")
    time.sleep(.3)
    apply_style(original_style)


open_window_elem = driver.find_element_by_id("openwindow")
highlight(open_window_elem)

最佳答案

对我来说效果很好。请注意,它仅在 0.3 秒内突出显示元素(添加 2 像素红色 边框),因此您可能会错过这种效果

你可以在函数中添加更多的参数,比如TimeToHighlight、Color、BorderSize:

def highlight(element, effect_time, color, border):
    """Highlights (blinks) a Selenium Webdriver element"""
    driver = element._parent
    def apply_style(s):
        driver.execute_script("arguments[0].setAttribute('style', arguments[1]);",
                              element, s)
    original_style = element.get_attribute('style')
    apply_style("border: {0}px solid {1};".format(border, color))
    time.sleep(effect_time)
    apply_style(original_style)

然后调用为

open_window_elem = driver.find_element_by_id("openwindow")
highlight(open_window_elem, 3, "blue", 5)

这将为元素添加蓝色 5 像素边框 3

关于Python Selenium - 高亮元素不做任何事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52207164/

相关文章:

python - 展平未知长度的元组

java - SessionNotFoundException : Session ID is null. 在调用 quit() 后使用 WebDriver? ( Selenium )

Java-Selenium 2 : Chromedriver - Exception calling driver. 管理().window().setPosition()

python - 如何使用 OpenCV 理解 Python 中的头部姿势估计角度?

python - 在python中复制文件

css - XPATH 或 CSS I 我在 span 标签中有一个复选框列表。我正在尝试选择一个特定的复选框

java - 如何获取gmail登录表单中包含错误消息的Web元素

java - Selenium Chrome 驱动程序 : NoClassDefFoundError: com/google/common/collect/Lists Exception

Python 记录 FileHandler 输出空白文件

java - ListIterator 或 Iterator 不会在 List 末尾停止