Transferred from: http://www.cnblogs.com/fnng/p/3230768.html
This section focuses on:
Invoking the JS method
- Execute_script (script, *args)
Synchronously executes JavaScript in the current window/frame
Script: Execution of JavaScript.
* Parameters: Applies to any JavaScript script.
Use:
Driver.execute_script (' Document.title ')
make the fast-seeding login user name input box red display :
#coding =utf-8from Selenium Import webdriverimport timedriver = Webdriver. Firefox () driver.get ("Http://passport.kuaibo.com/login/?referrer=http%3A%2F%2Fvod.kuaibo.com%2F%3Ft%3Dhome") # The input box for the user name is labeled Red js= "var Q=document.getelementbyid (\" user_name\ "); q.style.border=\" 1px solid red\ ";" #调用jsdriver. Execute_script (JS) time.sleep (3) driver.find_element_by_id ("user_name"). Send_keys ("username") driver.find_element_by_id ("User_pwd"). Send_keys ("password") driver.find_element_by_id ("Dl_an_submit"). Click () Time.sleep (3) driver.quit ()
JS Explanation:
Q=document.getelementbyid (\ "User_name\")
The ID of element q is user_name
Q.style.border=\ "1px solid red\
The style of element Q with a border of 1 pixels red
Hide elements
Js.html
(Keep the HTML file in the same directory as the execution script)
There are two common scenarios for executing JS:
- One is to directly execute JS on the page
- The other is to execute JS on an already positioned element.
#coding =utf-8from Selenium Import webdriver Import time,osdriver = Webdriver. Firefox () File_path = ' file:///' + os.path.abspath (' js.html ') driver.get (file_path) ###### #通过JS Hide selected elements ########## The first method: Driver.execute_script (' $ ("#tooltip"). FadeOut (); ') Time.sleep (5) #第二种方法: Button = Driver.find_element_by_class_name (' btn ') driver.execute_script (' $ (arguments[0]). FadeOut () ', button) Time.sleep (5) Driver.quit ()
JS Explanation:
A arguments object that is a special property of the calling object that is used to reference the arguments object. Arugments objects are like arrays.
The FadeOut () method uses a fade-out effect to hide the selected element, if the element is hidden.
PS: Can see JS can do selenium do things, but in what kind of automation can (or must) to JS help, I have not met. However, JS can be selenium to complete more powerful functions, it is indisputable.
In addition, did not learn JS before, so the JS code is very strange. If you have time, you are advised to add this knowledge to your classmates. UI Automation requires front-end technology.
Python Selenium--Invoke JS