使用JavaScript操作頁面元素

來源:互聯網
上載者:User

標籤:ror   實現   page   ==   name   nta   存在   bin   ase   

       在webdriver指令碼代碼中執行JavaScript代碼,來實現對頁面元素的操作。此種方式主要用於解決在某些情況下,頁面元素的.click()方法無法生效等問題。

#!usr/bin/env python  #-*- coding:utf-8 -*-  """ @author:   sleeping_cat@Contact : [email protected] """ #使用JavaScript操作頁面元素from selenium import webdriverfrom selenium.common.exceptions import WebDriverExceptionimport unittestimport traceback#匯入堆棧類import timeclass TestDemo(unittest.TestCase):    def setUp(self):        self.driver = webdriver.Chrome()    def test_executeScript(self):        url = ‘http://www.baidu.com‘        self.driver.get(url)        searchInputBoxJS = ‘document.getElementById("kw").value="光榮之路";‘
      #構造JavaScript尋找百度首頁的搜尋輸入框的代碼字串 searchButtonJS = ‘document.getElementById("su").click()‘
      #構造JavaScript尋找百度首頁的搜尋按鈕的代碼字串 try: self.driver.execute_script(searchInputBoxJS)
        #通過JavaScript代碼在百度首頁搜尋輸入框中輸入“光榮之路” time.sleep(2) self.driver.execute_script(searchButtonJS)
        #通過JavaScript代碼單擊百度首頁上的搜尋按鈕 time.sleep(2) self.assertTrue(‘百度百科‘ in self.driver.page_source) except WebDriverException as e: print("在頁面中沒有找到要操作的頁面元素" ,traceback.print_exc())#列印異常的堆棧資訊 except AssertionError as e: print(‘頁面不存在斷言的關鍵字串‘) except Exception as e: print(traceback.print_exc())#發生其他異常時,列印異常堆棧資訊 def tearDown(self): self.driver.quit()if __name__ == ‘__main__‘: unittest.main()

使用JavaScript操作頁面元素

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.