selenium+python自動化96-執行jquery報:$ is not defined

來源:互聯網
上載者:User

標籤:ima   iphone   ext   rip   utf-8   bdr   dev   query   classname   

前言

背景介紹:做wap頁面自動化的時候,把url地址直接輸入到瀏覽器(chrome瀏覽器有手機wap模式)上測試,有個按鈕死活點不到,用wap模式的觸摸事件也無法解決,後來想用jquery去執行點擊。
發現報$ is not defined。

# coding:utf-8# 上海-悠悠import timefrom selenium.webdriver.chrome.options import Optionsfrom selenium import webdriverfrom selenium.webdriver.common.touch_actions import TouchActionsurl="http://xxx"  # url地址省略mobile_emulation = {"deviceName": "iPhone 6"}  # 設定wap模式options=Options()options.add_experimental_option("mobileEmulation", mobile_emulation)driver=webdriver.Chrome()driver.set_window_size(400, 800)driver.get(url)time.sleep(3)el=driver.find_element_by_xpath("//*[text()=‘去支付‘]")TouchActions(driver).tap(el).perform()  # 觸摸事件# 執行jquery# jq = "$(‘.btn‘).click();"# driver.execute_script(jq)

仔細檢查了文法,發現文法沒問題,在瀏覽器上直接執行,也是能執行成功的。結果各種嘗試jquery不同的點擊方法,最終無法解決。後來換成js文法就搞定了。

遇到問題

1.在執行jquery指令碼的時候,報錯:

selenium.common.exceptions.WebDriverException: Message: unknown error: $ is not defined

2.後來嘗試了以下幾種方法都無果:

  • sleep時間加長一點,讓頁面載入完成

  • 換一種click方法:

$(‘.btn‘).trigger(‘click‘)
$(‘.btn‘).eq(0).trigger(‘click‘)

js解決

1.後來跟懂jquery的大神溝通了下,由於我訪問的是一個wap頁

2.目前很多H5的頁面,前端開發的架構如果使用的是vue,用$就不行,所以此方法行不通,後來用js就解決了

# coding:utf-8from selenium.webdriver.chrome.options import Optionsfrom selenium import webdriverurl = "https://www.xxx.xxx/"   # url地址省略driver=webdriver.Firefox()driver.set_window_size(400, 800)  # 設定視窗大小driver.get(url)# 執行jsjs = ‘document.getElementsByClassName("btn")[0].click();‘driver.execute_script(js)

selenium+python自動化96-執行jquery報:$ is not defined

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.