我正在尝试使用硒脚本单击网页上的按钮,但是使用此行却给我以下错误:
driver.find_element_by_class_name('btn-primary').click()
错误如下:
ElementNotInteractableException: Message: Element <button class="btn-primary btn-text sort-filter-clear-button" type="button"> could not be scrolled into view
按钮元素的HTML:
<button type="submit" class="btn-primary btn-action bookButton" id="bookButton" data-track="FLT.RD.Book.Bottom"><span class="btn-label">Continue Booking</span></button>
答案 0 :(得分:3)
尝试等待元素:
button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "bookButton")))
button.click()
它将等待至少10秒钟,直到元素可以单击为止。
注意:您必须添加一些导出:
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
编辑:,您也可以像这样尝试js执行器:
button = driver.find_element_by_id("bookButton")
driver.execute_script("arguments[0].click();", button)
如果您的按钮位于iframe/frame
内,则首先必须切换到此frame
,然后才能与该元素进行交互:
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.NAME("frame_name"))))
# do your stuff
button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.ID, "bookButton")))
button.click()
driver.switch_to.default_content() # switch back to default content
答案 1 :(得分:0)
按照您共享的 HTML 以及您提到的引导按钮,在尝试在所需元素上调用click()
时继续前进需要诱使 WebDriverWait 使元素可点击,并且您可以使用以下任一解决方案:
CSS_SELECTOR
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn-primary.btn-action.bookButton#bookButton>span.btn-label"))).click()
XPATH
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='btn-primary btn-action bookButton' and @id='bookButton']/span[@class='btn-label'][contains(.,'Continue Booking')]"))).click()
注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC