任務:在 Pyhton 中使用 selenium,我需要點擊鏈接,其中僅包含 href:
我的解決方案:
from selenium import webdriver
from credentials import DRIVER_PATH, LINK
from selenium.webdriver.common.by import By
import time
DRIVER_PATH = 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedgedriver.exe'
LINK = 'https://petstore.octoperf.com/actions/Catalog.action'
class Chart(object):
def __init__(self, driver):
self.driver = driver
self.fish_selection = "//a[@href='/actions/Catalog.action?viewCategory=&categoryId=FISH']"
def add_to_chart(self):
self.driver.find_element(By.XPATH, self.fish_selection).click()
time.sleep(3)
def setup():
return webdriver.Edge(executable_path=DRIVER_PATH)
def additiontest():
driver = setup()
driver.get(LINK)
driver.maximize_window()
welcome_page = Chart(driver)
welcome_page.add_to_chart()
driver.quit()
if __name__ == "__main__":
additiontest()
錯誤:
selenium.common.exceptions.NoSuchElementException:訊息:沒有這樣的元素:無法找到元素:{"method":"xpath","selector":"//a[@href='/actions/Catalog.action?viewCategory= &categoryId=CATS']"}(會話資訊:MicrosoftEdge=107.0.1418.42)
uj5u.com熱心網友回復:
- 該
href元素的值是動態變化的,因此您需要通過href屬性的固定部分來定位該元素。 - 您需要等待元素變為可點擊。
這應該會更好:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 20)
wait.until(EC.element_to_be_clickable((By.XPATH, "//a[contains(@href,'FISH')]"))).click()
UPD
根據您的專案結構,我認為您應該使用以下內容:
class Chart(object):
def __init__(self, driver):
self.driver = driver
self.fish_selection = "//a[contains(@href,'FISH')]"
self.wait = WebDriverWait(self.driver, 20)
def add_to_chart(self):
self.wait.until(EC.element_to_be_clickable((By.XPATH, self.fish_selection))).click()
time.sleep(3)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533007.html
上一篇:將資料從一個表拆分到另一個表
