我正在嘗試使用 selenium填寫 Uber 表單 ( 
我試圖用來XPath填寫表格,這里是代碼:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("user-data-dir=C:\\Users\\Zedas\\AppData\\Local\\Google\\Chrome\\User Data")
w = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=options)
w.get("https://m.uber.com/looking")
time.sleep(6)
w.get_element_by_xpath(f'"//*[@id="booking-experience-container"]/div/div[3]/div[2]/div/input"').send_keys("test")
但是,這是錯誤:
w.get_element_by_xpath(f'"//*[@id="booking-experience-container"]/div/div[3]/div[2]/div/input"').send_keys("test")
AttributeError: 'WebDriver' object has no attribute 'get_element_by_xpath'
如何修復此錯誤?
uj5u.com熱心網友回復:
get_element_by_xpath在 Selenium-Python 系結中沒有已知的方法。
請用
driver.find_element_by_xpath("xpath here")
此外,由于在find_element內部尋找隱式等待以等待并與 Web 元素互動。通常,已經觀察到在 Selenium 自動化中查找 web 元素/元素并不是一種一致的方法。
請使用顯式等待:
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "xpath here"))).send_keys("test")
您還需要這些匯入。
進口:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
您可以從此處閱讀有關等待的更多資訊
uj5u.com熱心網友回復:
w.get_element_by_xpath 應該 w.find_element_by_xpath
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("user-data-dir=C:\\Users\\Zedas\\AppData\\Local\\Google\\Chrome\\User Data")
w = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=options)
w.get("https://m.uber.com/looking")
time.sleep(6)
w.find_element_by_xpath(f'"//*[@id="booking-experience-container"]/div/div[3]/div[2]/div/input"').send_keys("test")
uj5u.com熱心網友回復:
這個錯誤資訊...
w.get_element_by_xpath(f'"//*[@id="booking-experience-container"]/div/div[3]/div[2]/div/input"').send_keys("test")
AttributeError: 'WebDriver' object has no attribute 'get_element_by_xpath'
暗示WebDriver物件沒有屬性 as get_element_by_xpath()。
您必須注意以下幾點:
- 如果您查看用于定位元素的各種WebDriver策略,則沒有您想要替換的方法
get_element_by_xpath()find_element_by_xpath() - 在呼叫
click()元素時,隱式等待不再有效,您需要將其替換為顯式等待,即WebDriverWait
解決方案
所以你的有效代碼塊將是:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
options = Options()
options.add_argument("user-data-dir=C:\\Users\\Zedas\\AppData\\Local\\Google\\Chrome\\User Data")
w = webdriver.Chrome(executable_path='chromedriver.exe', chrome_options=options)
w.get("https://m.uber.com/looking")
WebDriverWait(w, 20).until(EC.element_to_be_clickable((By.XPATH, f'"//*[@id="booking-experience-container"]/div/div[3]/div[2]/div/input"'))).send_keys("test")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/345989.html
