前言
背景介紹:做wap頁面自動化的時候,把url地址直接輸入到瀏覽器(chrome瀏覽器有手機wap模式)上測試,有個按鈕死活點不到,用wap模式的觸摸事件也無法解決,后來想用jquery去執行點擊。
發現報$ is not defined。
# coding:utf-8
# 作者:上海-悠悠
import time
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
from selenium.webdriver.common.touch_actions import TouchActions
url="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-8
# 作者:上海-悠悠
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
url = "https://www.xxx.xxx/" # url地址省略
driver=webdriver.Firefox()
driver.set_window_size(400, 800) # 設置窗口大小
driver.get(url)
# 執行js
js = 'document.getElementsByClassName("btn")[0].click();'
driver.execute_script(js)
seleniumQQ群:646645429
