1. 程式人生 > 其它 >python+selenium 自動匯入jQuery環境,解決網站沒有jQuery環境的問題

python+selenium 自動匯入jQuery環境,解決網站沒有jQuery環境的問題

技術標籤:常見問題seleniumjquerypython

有時我們會需要在selenium中執行jQuery語句,但並不是所有的網站都支援jQuery,如果沒有jQuery環境的問題,執行程式碼時就會報錯JavascriptException

使用以下程式碼即可解決該問題

    def import_jquery(self):
        """
        通過執行jquery語句來判斷當前網站是否具有jquery環境
        """
        try:  # 執行一段jquery測試程式碼
            self.
driver.execute_script("$('body').text()") except JavascriptException: # 報錯說明沒有接入jquery環境,執行接入 # 請求jquery線上原始碼包 resp = requests.get(r'https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js') # 直接執行jquery原始碼 self.driver.execute_script(resp.
content.decode()) else: # 沒報錯說明接入了jquery環境 ...

即插即用,十分方便