python - 如何通过 Selenium 和 Python 根据 HTML 单击引导按钮

标签 python selenium selenium-webdriver xpath css-selectors

我正在尝试使用 selenium 脚本单击网页上的按钮,但使用此行时出现以下错误:

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>

最佳答案

尝试等待元素:

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

关于python - 如何通过 Selenium 和 Python 根据 HTML 单击引导按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51252089/

相关文章:

python - 在 Python 中使用 Selenium 检查页面是否切换到另一个页面

selenium - 按子文本选择节点

selenium - 使用 css 选择器在精确元素中按精确文本查找元素

python - selenium move_to_element 并不总是鼠标悬停

python - 如何将列表中的元素放入 Python 3 中的列表列表?

python - RQ 属性错误 : 'module' object has no attribute

javascript - 如何单击子元素

docker - 在 headless (headless) chrome Docker 中获取运行 selenium 的空页面

Python dateutil 解析器,忽略字符串的非日期部分

python - 用 pandas 和 numpy Python 替换列表推导式