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