Selenium:如何单击按钮[关闭]

问题描述 投票:0回答:1

我有一个网页,其中有一个按钮,我需要在 Python 中使用 Selenium 单击。该按钮是一个具有

input
class
name
属性的
type
元素。尽管尝试了与
find_element
的各种组合,我仍然收到“无法定位元素”错误。单击后,该按钮应在 Chrome 查看器中打开 PDF 文件。之后,我计划发送按键 Ctrl + S 来下载 PDF。你能帮我找到正确的代码吗?

python selenium-webdriver button click
1个回答
-1
投票

“无法定位元素”问题的最常见原因是与时间相关或定位器不正确。另外,请确保将“btn-primary”替换为按钮的实际类名,将“pdf_viewer_url_fragment”替换为 URL 中指示 PDF 查看器已加载的唯一部分。

以下是如何找到并单击您共享的按钮的基本示例:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# Initialize the Chrome webdriver
driver = webdriver.Chrome()

# Open the webpage
driver.get("your_webpage_url_here")

# Locate and click the button using its class attribute
button_locator = (By.CLASS_NAME, "your_button_class_here")  # Replace "your_button_class_here" with the actual class of your button
try:
    button = WebDriverWait(driver, 10).until(EC.element_to_be_clickable(button_locator))
    button.click()
except Exception as e:
    print(f"Error clicking the button: {e}")
    driver.quit()

# Wait for the PDF viewer to load (you might need to adjust the wait time)
pdf_viewer_url_fragment = "pdf_viewer_url_fragment"  # Replace with a unique part of the URL indicating the PDF viewer
try:
    WebDriverWait(driver, 10).until(EC.url_contains(pdf_viewer_url_fragment))
except Exception as e:
    print(f"Error waiting for PDF viewer: {e}")
    driver.quit()

# Send keys "Ctrl + S" to save the PDF
try:
    webdriver.ActionChains(driver).key_down(Keys.CONTROL).send_keys("s").key_up(Keys.CONTROL).perform()
except Exception as e:
    print(f"Error sending keys: {e}")
    driver.quit()

# Close the browser
driver.quit()
© www.soinside.com 2019 - 2024. All rights reserved.