python - 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:
HTML:
<a href="/cart" class="cart-heading">Cart</a>
HTML Snapshot:
解决方案
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
推荐阅读
- django - 在我将 formset 属性添加到 modelformset_factory() 之前,我的模型表单集工作正常
- r - 在 R 中为 tiff() 输出调整和选择适当大小的提示和技巧;保存时图像与文本经常不成比例
- python - 如何在 QMainWindow 中隐藏空的中央小部件
- caching - 在内存层次结构的上下文中,为什么有“写未命中策略”,而没有“读未命中策略”?
- windows - 从批处理文件启动的文件夹不是活动窗口
- bash - GitBash:无法更改目录
- python - 在python3中取消扭曲图像
- php - Vue / Laravel - 导入 CDN vuetify 而不是 npm install
- sql-server - 编写发布脚本后,SQL Server 在某些表上合并复制和垂直分区
- ionic-framework - 如何在桌面平台的 ionic4 项目中显示谷歌广告?