【问题标题】:Python Selenium - highlight element doesn't do anythingPython Selenium - 高亮元素不做任何事情
【发布时间】:2019-02-11 21:35:44
【问题描述】:

我正在尝试使用 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)

【问题讨论】:

    标签: python selenium selenium-chromedriver highlight


    【解决方案1】:

    对我来说很好用。请注意,它仅在 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

    【讨论】:

    • 你完全正确!非常感谢 Andersson,非常感谢您的帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-23
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多