我正在尝试购买产品,因此需要将其添加到正在运行的购物车中,但是当我尝试单击结帐按钮时,会出现错误。
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)
答案 0 :(得分:1)
这是因为您需要等待硒检出并单击“检出”按钮
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
的课,这里有更多信息:Wait until page is loaded with Selenium WebDriver for Python