我在使用 SELENIUM 查找元素时遇到问题

问题描述 投票:0回答:1

我试图找到一个在 HTML 内部相当深的元素,并且我尝试了 Xpath、类、链接文本和 css 方法以及这些方法中的任何一个。我总是得到同样的错误:selenium.common.exceptions.NoSuchElementException。

我在这里发送 HTML:

enter image description here

我尝试的最后一件事是:

selector = driver.find_element(By.XPATH, '/html/body/div[1]/header/div/div/div[3]/div[1]/nav/section[2]/ul/li[4]/a[@class="mega-menu__link"]')
        selector.send_keys(Keys.RETURN)
        selector.click()
        time.sleep(5)
python html selenium-webdriver xpath
1个回答
0
投票

在没有看到该页面的情况下,很难确定问题是什么,但可能有 1 或 2 件事......

  1. 定位器可能不正确。我会尝试

    CSS 选择器

    a[href*='upcoming.html']
    a.mega-menu__link
    

    XPath

    a[text()='Upcoming']
    
  2. 在搜索元素之前添加等待以确保页面已完成加载

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.wait import WebDriverWait
    
    ...
    
    wait = WebDriverWait(driver, 10)
    wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[href*='upcoming.html']"))).click()
    
© www.soinside.com 2019 - 2024. All rights reserved.