Execute the JavaScript code in the Webdriver script code to implement the action on the page element. This approach is primarily intended to address issues such as the. Click () method of a page element that is not valid in some cases.
#!usr/bin/env python#-*-coding:utf-8-*-"""@author: sleeping_cat@contact: [email protected]""" #manipulating page elements with JavaScript fromSeleniumImportWebdriver fromSelenium.common.exceptionsImportwebdriverexceptionImportUnitTestImportTraceback#Import Stack classImport TimeclassTestdemo (unittest. TestCase):defsetUp (self): Self.driver=Webdriver. Chrome ()defTest_executescript (self): URL='http://www.baidu.com'self.driver.get (URL) searchinputboxjs='document.getElementById ("kw"). Value= "The Road of Glory";'
#construct JavaScript to find the code string for the search input box on Baidu homepageSearchbuttonjs ='document.getElementById ("su"). Click ()'
#construct JavaScript to find the code string for the search button on the homepage of Baidu Try: Self.driver.execute_script (SEARCHINPUTBOXJS)
#enter "Glorious Road" in the Baidu homepage search input box via JavaScript codeTime.sleep (2) Self.driver.execute_script (SEARCHBUTTONJS)
#Click the Search button on the Baidu homepage via JavaScript codeTime.sleep (2) Self.asserttrue ('Baidu Encyclopedia' inchSelf.driver.page_source)exceptwebdriverexception as E:Print("page elements to manipulate are not found on the page", Traceback.print_exc ())#to print stack information for an exception exceptAssertionerror as E:Print('The page does not have an assertion keyword string') exceptException as E:Print(Traceback.print_exc ())#Print exception stack information when other exceptions occur defTearDown (self): Self.driver.quit ()if __name__=='__main__': Unittest.main ()
Manipulating page elements with JavaScript