高亮显示当前webdriver正在操作的元素,可以使用js代码来完成,两种写法:
driver.execute_script(‘arguments[0].style.border="2px solid red";‘, ele)
driver.execute_script(‘arguments[0].setAttribute("style", "border: 2px solid red");‘, ele)
ele是通过driver定位到的元素,传入这个元素,arguments[0]就接受第一个传参,即该元素
至于高亮的样式都可以自己用css指定
但是这样只能高亮显示,在同一页面操作多个元素时会导致一片都高亮显示,所以自己研究了下,将高亮显示和还原方法放到了类中,代码如下:
from selenium import webdriver
from time import sleep
class HighLight:
# 初始化需要传入操作的driver
def __init__(self, dr):
self.driver = dr
self.border = None
self.ele = None
def highlight(self, ele):
self.ele = ele
# 记录元素修改前的border样式
self.border = self.ele.value_of_css_property('border')
# 修改border样式,高亮显示
self.driver.execute_script('arguments[0].style.border="2px solid red";', self.ele)
def reset(self):
if self.border is None or self.ele is None:
return
# 将border样式还原
self.driver.execute_script(f'arguments[0].style.border="{self.border}";', self.ele)
self.ele = None
self.border = None
with webdriver.Chrome() as driver:
hl = HighLight(driver)
driver.get('https://www.sogou.com/')
driver.maximize_window()
driver.implicitly_wait(5)
query = driver.find_element_by_id('query')
hl.highlight(query)
query.send_keys('123')
hl.reset()
sleep(1)
submit = driver.find_element_by_id('stb')
hl.highlight(submit)
submit.click()
hl.reset()
sleep(3)
原文地址:https://www.cnblogs.com/milesma/p/12333841.html
时间: 2024-10-18 21:10:45