【问题标题】:selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element using Selenium and Pythonselenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:无法使用 Selenium 和 Python 定位元素
【发布时间】:2018-12-29 04:49:13
【问题描述】:

无法与 href 链接交互。

代码试验:

browser = webdriver.Chrome() 
browser.implicitly_wait(5) 
browser.get(URL) 
webbrowser.open(URL) 
#if Size == 'Large': 
ClickS =browser.find_element_by_id('product-select').click() 
SizeS = browser.find_element_by_xpath("//option[@value='12218866696317']").click() 
#Send to cart 
AddtoCart = browser.find_element_by_css_selector("input[type='submit']").click() 
GotoCart = browser.find_element_by_partial_link_text("Cart").click()

代码和错误快照:

HTML:

<a href="/cart" class="cart-heading">Cart</a>

HTML 快照:

【问题讨论】:

  • 请将代码本身添加到您的问题中,而不是屏幕截图
  • 当我复制粘贴我的代码时会出现问题,它不会让我发布它
  • 您的元素似乎被隐藏了。你能发布 HTML 代码而不是 snap
  • 欢迎来到 Stack Overflow!作为新用户,您可能应该阅读tour 以熟悉该站点。输入问题时有formatting help available;请立即阅读并edit您的帖子。如果您的未指定(“a”)问题是您的帖子似乎主要由 code 组成,那么现在它主要由 images 组成,这不是改进。该信息旨在鼓励您用文字描述问题所在以及您尝试解决的问题。

标签: python selenium-webdriver xpath css-selectors webdriverwait


【解决方案1】:

此错误消息...

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element {"method":"link text","selector":"Cart"}

...暗示 ChromeDriver 无法根据以下行找到所需的元素:

GotoCart = browser.find_element_by_link_text("Cart").click()

解决方案

您需要诱导 WebDriverWait 以使所需的元素可点击,您可以使用以下任一解决方案:

  • 使用LINK_TEXT

    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Cart"))).click()
    
  • 使用CSS_SELECTOR

    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "section#header a.cart-heading[href='/cart']"))).click()
    
  • 使用XPATH

    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//section[@id='header']//a[@class='cart-heading' and @href='/cart']"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

PS:可以在Selenium “selenium.common.exceptions.NoSuchElementException” when using Chrome找到详细讨论

【讨论】:

  • 非常感谢它现在可以正常工作,但我不得不问一下你是如何获得 css 选择器的“section#header a.cart-heading[href='/cart']”和 xpath 的跨度>
  • CssSelector 在您提供的图像中非常明显。
【解决方案2】:

错误位于堆栈跟踪的底部,它无法从您提供的链接文本中找到元素。这可能与此人遇到的问题相同,即 python 运行速度过快而页面未完全加载:How to use find_element_by_link_text() properly to not raise NoSuchElementException?

所以只需在您设置browser 的行之后添加browser.implicitly_wait(10)

【讨论】:

    猜你喜欢
    • 2019-10-25
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多