Web automation: how to send js instructions in 8.2 selenium

In the previous section 8.1 How to send js commands in the browser, we learned about some commonly used js commands.
In this section, continue to learn how to send js commands in selenium.

Just master this fixed syntax:

driver.execute_script(js_code)   # js_code 换成你需要的js指令

For example: Clear the content of the Baidu homepage

from selenium import webdriver
import time

driver = webdriver.Chrome()  # 初始化一个谷歌浏览器
driver.maximize_window()  # 浏览器窗口最大化
driver.get("http://www.baidu.com")   # 打开一个百度网页

time.sleep(10)
js_code = 'document.body.innerText = ""'   # 清空网页
driver.execute_script(js_code)
time.sleep(2)

Precautions:
1. Generally, it takes a while between the python code and the js code, otherwise an error may occur if the js code is executed before the page is loaded.
2. time.sleep(10) cannot be replaced with implicit waiting (wait for the element to appear before operating); explicit waiting can be used (wait for the URL to be a certain value before executing)

Guess you like

Origin blog.csdn.net/weixin_48415452/article/details/120272016