首页 > 解决方案 > selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element using Selenium and Python

问题描述

Unable to interact with href link.

Code trials:

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()

Code and Error snapshot:

enter image description here

HTML:

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

HTML Snapshot:

enter image description here

标签: pythonselenium-webdriverxpathcss-selectorswebdriverwait

解决方案


This error message...

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

...implies that the ChromeDriver was unable to locate the desired element as per the line:

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

Solution

You need to induce WebDriverWait for the desired element to be clickable and you can use either of the following solutions:

  • Using LINK_TEXT:

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

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

    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//section[@id='header']//a[@class='cart-heading' and @href='/cart']"))).click()
    
  • Note : You have to add the following imports :

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

PS: You can find a detailed discussion in Selenium “selenium.common.exceptions.NoSuchElementException” when using Chrome


推荐阅读