我的Selenium Python脚本无法单击“添加到购物车”按钮。
HTML代码:
<input type="button" value="Add to cart" title="Add to cart"
class="button-2 product-box-add-to-cart-button" onclick="AjaxCart.addproducttocart_catalog
('/addproducttocart/catalog/18/1/1');return false;">
我的脚本:
inputElement = driver.find_element_by_xpath("/html/body/div[7]/div[4]/div[2]/div[1]/div/div[2]/div[4]/div/div[3]/div/div[2]/div[3]/div[2]/input[3]")
inputElement.click()
这是我得到的错误:
File "C:\Users\Raghav\AppData\Local\Programs\Python\Python36-32\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 242, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Element <input type="button" value="Add to cart" title="Add to cart" class="button-2 product-box-add-to-cart-button" onclick="AjaxCart.addproducttocart_catalog('/addproducttocart/catalog/18/1/1');return false;"> is not clickable at point (1334, 635). Other element would receive the click: <div class="page-loader" style="opacity: 0.924946;">...</div>
答案 0 :(得分:2)
根据您共享的HTML,单击需要诱使 WebDriverWait 的元素,以使所需的元素可点击,您可以使用以下解决方案:< / p>
CSS_SELECTOR
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.button-2.product-box-add-to-cart-button[title='Add to cart']"))).click()
XPATH
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@class='button-2 product-box-add-to-cart-button' and @title='Add to 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
答案 1 :(得分:0)
尝试一下:
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "/html/body/div[7]/div[4]/div[2]/div[1]/div/div[2]/div[4]/div/div[3]/div/div[2]/div[3]/div[2]/input[3]")))
element.click()
答案 2 :(得分:0)
您的xpath是正确的,它可以获取值,但无法单击。为此,您可以使用操作方法单击它。
您需要使用操作类替换click事件,这将解决此异常
点击的操作方法:
from selenium.webdriver.common.action_chains import ActionChains
actions = ActionChains(driver)
actions.move_to_element("Element to Click").click().perform()
但是,您使用了绝对xpath,这绝对不是一个好主意。您需要使用相对xpath,如下所示或 @DebanjanB 所述。
相对xpath而非绝对值:
//input[@title='Add to cart' and @value='Add to cart']