1. 程式人生 > >selenium 模擬手機瀏覽器操作 click點選/tap觸控 元素無效 的解決方法

selenium 模擬手機瀏覽器操作 click點選/tap觸控 元素無效 的解決方法

我遇到的問題

  1. 獲取到 登入按鈕 的 xpath,且可以保證 xpath 正確無誤
  2. 點選 登入按鈕, 無法正常跳轉到 登入成功頁
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

mobile_emulation = {"deviceName": "iPhone X"}
options = Options()
options.add_experimental_option("mobileEmulation", mobile_emulation)
driver = webdriver.Chrome(chrome_options=options) driver.get("https://xxx.com") #輸入帳號密碼 driver.find_element_by_xpath("//*[@id='email-login-input']/div/div[2]/input").send_keys("user") driver.find_element_by_xpath("/html/body/div/div/div[2]/div[2]/div[2]/div[4]/div/div/div[2]/input").send_keys("password") #點選登入按鈕 driver.
find_element_by_xpath("/html/body/div/div/div[2]/div[2]/div[2]/button").click() #點選後,無任何反應
  1. 觸控 登入按鈕, 無法正常跳轉到 登入成功頁
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
from selenium.webdriver.common.touch_actions import TouchActions

mobile_emulation = {
"deviceName": "iPhone X"} options = Options() options.add_experimental_option("mobileEmulation", mobile_emulation) driver = webdriver.Chrome(chrome_options=options) driver.get("https://xxx.com") #輸入帳號密碼 driver.find_element_by_xpath("//*[@id='email-login-input']/div/div[2]/input").send_keys("user") driver.find_element_by_xpath("/html/body/div/div/div[2]/div[2]/div[2]/div[4]/div/div/div[2]/input").send_keys("password") #單次觸控 登入按鈕 Action = TouchActions(driver) loginButton = driver.find_element_by_xpath("/html/body/div/div/div[2]/div[2]/div[2]/button") Action.tap(loginButton) Action.perform() #觸控後,有觸控的反饋,但仍無法跳轉到 登入成功頁
  1. 使用簡單粗暴的方法send_keys(Keys.ENTER),模擬點選 回車鍵,可正常登入
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
from selenium.webdriver.common.keys import Keys

mobile_emulation = {"deviceName": "iPhone X"}
options = Options()
options.add_experimental_option("mobileEmulation", mobile_emulation)
driver = webdriver.Chrome(chrome_options=options)
driver.get("https://xxx.com")
#輸入帳號密碼
driver.find_element_by_xpath("//*[@id='email-login-input']/div/div[2]/input").send_keys("user")
driver.find_element_by_xpath("/html/body/div/div/div[2]/div[2]/div[2]/div[4]/div/div/div[2]/input").send_keys("password")
#定位“登入按鈕”,按“回車鍵”
loginButton = driver.find_element_by_xpath("/html/body/div/div/div[2]/div[2]/div[2]/button")
loginButton.send_keys(Keys.ENTER)
#點選 “回車鍵” 後,可正常跳轉到 登入成功頁,問題解決

webdriver 的Keys()類提供鍵盤上所有按鍵的操作

from selenium.webdriver.common.keys import Keys
#在使用鍵盤按鍵方法前需要先匯入keys 類包。
#下面經常使用到的鍵盤操作:
send_keys(Keys.BACK_SPACE) #刪除鍵(BackSpace)
send_keys(Keys.SPACE) #空格鍵(Space)
send_keys(Keys.TAB) #製表鍵(Tab)
send_keys(Keys.ESCAPE) #回退鍵(Esc)
send_keys(Keys.ENTER) #回車鍵(Enter)
send_keys(Keys.CONTROL,'a') #全選(Ctrl+A)
send_keys(Keys.CONTROL,'c') #複製(Ctrl+C)