[英]Selenium WebDriver “find_element_by_xpath” on WebElement
[英]Selenium find_element_by_xpath
我正在嘗試購買產品,因此需要將其添加到正在運行的購物車中,但是當我嘗試單擊結帳按鈕時出現錯誤。
driver = webdriver.Chrome(r'C:\Users\x\OneDrive\Desktop\chromedriver.exe')
driver.get('https://feature.com/products/billionaire-boys-club-kids-bb-copilot-polo-black')
driver.find_element_by_xpath('//div[@data-value="3T"]').click()
driver.find_element_by_xpath('//button[@class="AddToCart default-btn"]').click()
在這部分之前,它仍然有效,但是嘗試檢出它是無效的。
driver.find_element_by_xpath('//button[@name="checkout"]').click()
<button type="submit" class="btn--secondary btn--full cart__checkout"
name="checkout" value="Check Out →">
Check Out
</button>
我收到此錯誤:
File "C:\Users\x\OneDrive\Desktop\Sp\Snx.py", line 35, in <module>
driver.find_element_by_xpath('//button[@name="checkout"]').click()
File "C:\Users\x\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 394, in find_element_by_xpath
return self.find_element(by=By.XPATH, value=xpath)
File "C:\Users\x\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 978, in find_element
'value': value})['value']
File "C:\Users\x\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\x\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//button[@name="checkout"]"}
(Session info: chrome=74.0.3729.131)
(Driver info: chromedriver=74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729@{#29}),platform=Windows NT 10.0.17134 x86_64)
這是因為您需要等待硒檢出並單擊“ checkout”按鈕
import time
from selenium import webdriver
driver = webdriver.Chrome(r'C:\Users\x\OneDrive\Desktop\chromedriver.exe')
driver.get('https://feature.com/products/billionaire-boys-club-kids-bb-copilot-polo-black')
driver.find_element_by_xpath('//div[@data-value="3T"]').click()
driver.find_element_by_xpath('//button[@class="AddToCart default-btn"]').click()
time.sleep(2)
cart_container = driver.find_element_by_id('CartContainer')
cart_container.find_element_by_name('checkout').click()
在本示例中,我使用了time.sleep(secs)
,但不能保證該元素已經顯示。
如果您想改進,這里有一個叫做WebDriverWait
的類,更多信息在這里: 等待,直到頁面被Selenium WebDriver for Python加載。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.