selenium 仅单击带有href的链接

xzlaal3s  于 2022-11-24  发布在  其他
关注(0)|答案(1)|浏览(227)

**任务:**在Pyhton中使用 selenium ,我需要单击链接,该链接仅包含href:x1c 0d1x
我的解决方案:

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:消息:没有此元素:找不到元素:{“方法”:“xpath”,“选择器”:“//a[@href ='/actions/Catalog.action?视图类别=&类别ID = CATS']"}(会话信息:微软边缘服务器=107.0.1418.42)

vql8enpb

vql8enpb1#

1.该元素的href值是动态变化的,因此需要通过href属性的固定部分来定位该元素。
1.您需要等待元素变为可单击。
这样做效果会更好:

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)

相关问题