Selenium+python automation 96-execute jquery report: $ is not defined

foreword

Background introduction: When doing wap page automation, directly input the url address into the browser (chrome browser has mobile phone wap mode) to test, there is a button that can't be clicked, and the touch event in wap mode can't be solved. Use jquery to perform the click.
It is found that $ 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) 

I checked the grammar carefully and found that the grammar is fine, and it can be executed successfully on the browser. As a result, I tried various jquery click methods, and finally could not solve it. Later, it was done by changing to js syntax.

Encounter problems

1. When executing the jquery script, an error is reported:

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

2. Later I tried the following methods to no avail:

  • Sleep a little longer to let the page load complete

  • Another click method:

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

js to solve

1. Later, I communicated with the god who understands jquery, because I was visiting a wap page

2. At present, for many H5 pages, if the front-end development framework uses vue, it will not work with $, so this method will not work, and then it will be solved with 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)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325341384&siteId=291194637