Webdriver, need to use JS, no need to introduce a package about JS can be used in the Webdriver script code to execute JavaScript code, to implement the operation of the page elements. This method is primarily intended to address issues such as the. Click () method of a page element that is not valid in some cases.
#Encoding=utf-8 fromSeleniumImportWebdriver fromSelenium.common.exceptionsImportwebdriverexceptionImportUnitTestImportTracebackImport TimeclassTestdemo (unittest. TestCase):defsetUp (self):#start the Chrome browser #self.driver = Webdriver. Chrome (Executable_path = "C:\\chromedriver")Self.driver = Webdriver. Ie (Executable_path ="E:\\iedriverserver") defTest_executescript (self): URL="http://www.sogou.com" #Visit Baidu Homepageself.driver.get (URL)#construct JavaScript to find the code string for the search input box on Baidu homepageSEARCHINPUTBOXJS ="document.getElementById (' query '). Value= ' The Road of Glory ';" #construct JavaScript to find the code string for the search button on the homepage of BaiduSearchbuttonjs ="document.getElementById (' STB '). Click ()" Try: #enter "Glorious Road" in the Baidu homepage search input box via JavaScript codeself.driver.execute_script (SEARCHINPUTBOXJS) time.sleep (2) #Click on the Search button on the Baidu homepage via JavaScript codeself.driver.execute_script (SEARCHBUTTONJS) time.sleep (2) self.asserttrue (U"the road to glory" inchSelf.driver.page_source)exceptwebdriverexception, E:#A Webdriverexception exception is thrown when the location fails PrintU"page elements to manipulate are not found on the page", Traceback.print_exc ()exceptAssertionerror, E:PrintU"The page does not have an assertion keyword string" exceptException, E:#Print exception stack information when other exceptions occur PrintTraceback.print_exc ()defTearDown (self):#Exit IE Browserself.driver.quit ()if __name__=='__main__': Unittest.main ()
Explain:
>>> Try:
... 1/0
... except:
.. print "Error"
...
Error
>>> Import Traceback
>>> Try:
... 1/0
... except:
... traceback.print_exc ()
...
Traceback (most recent):
File "<stdin>", line 2, in <module>
Zerodivisionerror:integer division or modulo by zero
#Traceback可以打印出出错的具体错误信息和位置
Webdriver Advanced Apps-use JavaScript to manipulate page elements