单击下订单按钮后,我尝试向下滚动并单击下一页上的 Purchase 按钮:
https://www.demoblaze.com/cart.html
但我一直遇到以下错误:
org.openqa.selenium.ElementNotInteractableException: Element <button class="btn btn-primary" type="button"> could not be scrolled into view
我尝试过使用
JavascriptExecutor
但我无法让它工作。对我做错了什么有什么建议吗?
这是我最近使用的代码
JavascriptExecutor js = (JavascriptExecutor) getDriver();
WebElement element = getDriver().findElement(By.cssSelector("button.btn-primary"));
WebDriverWait wait = new WebDriverWait(getDriver(), Duration.ofSeconds(5));
js.executeScript("arguments[0].scrollIntoView(true);", element);
element.click();
我不知道我的建议是否对您有帮助,但无论如何我都会尝试。首先,通过连接到指示的页面,我注意到您不必向下滚动页面即可单击第一个
Place Order
按钮,因为我位于页面右侧的顶部。因此,滚动是没有用的。随后,单击按钮后,我确保它等待模式的打开,然后必须填写该模式(我手动完成了这部分以了解它是否有效,但我没有实现任何东西来做到这一点自动;我希望你已经完成了)。最后,填写各个字段后,单击Purchase
按钮,这将实际确认订单成功。如上所述,我专门插入了 time.sleep 来为您提供正在发生的情况的图形反馈。我还指出,如果一开始运行此代码需要一些时间,则可能是因为它正在安装正确版本的WebDriver
。
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
import time
def start_selenium():
chrome_service = Service()
chrome_options = webdriver.ChromeOptions()
chrome_driver = webdriver.Chrome(service=chrome_service)
return chrome_driver
def click_purchase_button():
page = "https://www.demoblaze.com/cart.html"
selenium_driver = start_selenium()
try:
selenium_driver.get(page)
WebDriverWait(selenium_driver, 60).until(EC.presence_of_element_located((By.CSS_SELECTOR, "button[class*='btn btn-primary']")))
place_order_button = selenium_driver.find_element(By.XPATH, "//*[@id='page-wrapper']/div/div[2]/button")
place_order_button.click()
time.sleep(30)
WebDriverWait(selenium_driver, 60).until(EC.visibility_of_element_located((By.ID, "orderModal")))
purchase_button = selenium_driver.find_element(By.XPATH, "//button[contains(text(), 'Purchase')]")
selenium_driver.execute_script("arguments[0].click();", purchase_button)
time.sleep(15)
selenium_driver.quit()
except Exception as e:
print(e)
finally:
selenium_driver.quit()
click_purchase_button()