Web automation: 8.1 How to send js commands in the browser

Suggested reading objects: no front-end foundation, no Javascript, novices in web automation (selenium)

Web automated testing, why do you need to learn js instructions after knowing selenium?

The previous sections talked about the operation of selenium, but there are still some browser operations (such as: page scrolling, time selection, files, etc.) that cannot be directly implemented through selenium. Therefore, we also need to understand some simple js commands, and let the browser perform corresponding operations by sending js commands.

what is js?

HTML is only responsible for statically displaying
the programming language used by Javascript front-end engineers. Role: Let web pages achieve dynamic effects.

Almost all browsers have a built-in Javascript execution environment, so you can write and execute js commands directly in the browser-developer tools-Console.

Schematic diagram of selenium

insert image description here

How does js control the browser?

DOM (Document object model)
document object, representing the current entire web page. Enter document, and the code of this web page will be returned.
I won’t talk about the details here, if you are interested, you can check the information by yourself (mainly I am also a front-end novice, I am afraid that I will mislead everyone if I don’t know clearly)

practise:

1. Define a name and print the name

Syntax for printing: console.log(name)
insert image description here

2. Element positioning

In python, find_element('id', 'kw') is converted into js command getElementById("kw") through webdriver, so the two effects are the same.
The js command can only modify the front-end display, and the page will be restored to the original after refreshing.

# 定位百度输入框元素
el = document.getElementById("kw")  

# 修改该元素的value值(selenium只能获取属性,不能修改属性)
el.value = '花测试'		

# 输入框变置灰不能修改的状态
el.disabled = true

# 输入框变回可输入状态		
el.disabled = false	

# 清空网页。该方式可以更新或修改,甚至重写整个html
document.body.innerText = ''  

Guess you like

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