Selenium automates the highlighting of positioned elements

In debugging Selenium scripts, sometimes it is not clear whether the correct element is located because the operation is too fast or the operation is not obvious. We can highlight the positioned elements by adding styles to the positioned elements by executing js.

In Selenim Webdriver, you can execute JavaScript code through driver.executue_scirpt(). The executed JavaScript code supports passing in parameters, and you can even pass in positioned elements, such as: , use
exectue_script('js脚本', 参数1,参数2,参数3...)arguments[n] in the JavaScript script string To indicate the number of parameters to match.

The sample code is as follows:

from selenium import webdriver
from time import sleep

STYLE = "background: green; border: 2px solid red;"  # 高亮的样式

def find(driver, by, expr):
    element = driver.find_element(by, expr)
    driver.execute_script("arguments[0].setAttribute('style', arguments[1]);",element, STYLE)  
    return element

driver = webdriver.Chrome()
driver.get('https://www.baidu.com/')

find(driver, 'id', 'kw').send_keys("博客园 韩志超")
find(driver, 'id', 'su').click()

sleep(3)
driver.quit()

In the above code,
by is only a positioning method, and supports 'id', 'xpath', 'name', 'class name', 'link text', 'partial link text', 'css selector', and expr is the positioning expression corresponding to the element Mode.
driver.execute_script("arguments[0].setAttribute('style', arguments[1]);",element, STYLE)
Replace the positioned element with arguments[0], replace arguments[1] with STYLE, and add a highlight style to the element.

After execution, the result is as follows: 

Practical case

Optical theory is useless, you have to learn to follow along, and you have to do it yourself, so that you can apply what you have learned to practice. At this time, you can learn from some actual combat cases.

If it is helpful to you, please like and collect it to give the author an encouragement. It is also convenient for you to quickly find it next time.

If you don’t understand, please consult the small card below. The blogger also hopes to learn and progress with like-minded testers

At the right age, choose the right position, and try to give full play to your own advantages.

My road of automated test development is inseparable from the plan of each stage along the way, because I like planning and summarizing,

Test and develop video tutorials, study notes and receive portals! ! !

Guess you like

Origin blog.csdn.net/m0_59868866/article/details/130266314