繁体   English   中英

硒find_element_by_xpath

[英]Selenium find_element_by_xpath

我正在尝试购买产品,因此需要将其添加到正在运行的购物车中,但是当我尝试单击结帐按钮时出现错误。

打开chromedriver

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM