点击一个困难的按钮selenium python

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

这里我给大家分享一下我需要点击的具体按钮的网页和html。这看起来很容易,因为有一个“输入类”、一个“名称”和一个“类型”。然而,我与 find_element 一起使用的所有组合都会导致“无法找到元素”。您能帮忙使用正确的代码吗?单击此按钮后,我应该在 Chrome 查看器中看到完整的 pdf 文件。然后我将尝试发送键“ctrl + s”以便能够下载它,这是我的最终目的。

enter image description here

我尝试了很多种查找元素的操作组合,但都没有成功。

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

“无法定位元素”问题的最常见原因是与时间相关或定位器不正确。另外,请确保将“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.