[英]selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element error using Selenium through Python
[英]selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element using Selenium and Python
無法與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快照:
此錯誤消息...
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 : 使用Chrome時,您可以在Selenium“ selenium.common.exceptions.NoSuchElementException”中找到詳細的討論
該錯誤位於堆棧跟蹤的底部,無法從您提供的鏈接文本中找到該元素。 這個人可能遇到了同樣的問題,即python的運行速度太快並且頁面沒有完全加載: 如何正確使用find_element_by_link_text()而不引發NoSuchElementException?
因此,只需在設置browser
的行之后添加browser.implicitly_wait(10)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.