繁体   English   中英

无法使用 Selenium 单击按钮

[英]Not able to click on the button using Selenium

 <button class="css-obkt16-button" type="button"><span class="css-1mhnkuh">Download CSV</span></button>

我正在尝试单击突出显示的按钮“下载 CSV 在此处输入图像描述 具有上述 HTML 代码并将 csv 文件保存在某个特定位置,但我无法这样做。 该文件正在下载文件夹中下载。

我的 python 代码:

def scrape_data():
    DRIVER_PATH = r"C:\chrome\chromedriver.exe"
    driver = webdriver.Chrome(DRIVER_PATH)
    driver.get('Link to the dashboard')
    time.sleep(20)    
    buttons = driver.find_element(By.XPATH,"//button/span[text()='Download CSV']")
    time.sleep(5)
    driver.execute_script("arguments[0].click();", buttons)
    driver.quit()

所以请建议一种通过按钮文本搜索的方法)并将文件保存到特定位置??

要将文件下载到特定位置,您可以像打击一样尝试。

from selenium.webdriver.chrome.options import Options

options = Options()
options.add_experimental_option("prefs", {
  "download.default_directory": r"C:\Data_Files\output_files"
  })
s = Service('C:\\BrowserDrivers\\chromedriver.exe')
driver = webdriver.Chrome(service=s, options=options)
  1. 您不应该使用像time.sleep(20)这样的硬编码睡眠。 应该改用WebDriverWait expected_conditions
  2. 在大多数情况下,在获取元素和单击它之间添加睡眠并没有帮助。
  3. 除非你真的别无选择,否则永远不要使用带有 JavaScript 的点击元素。
  4. 如果您尝试单击的按钮位于可见屏幕区域内并且定位器是唯一的,这应该可以工作。
def scrape_data():
    DRIVER_PATH = r"C:\chrome\chromedriver.exe"
    driver = webdriver.Chrome(DRIVER_PATH)
    wait = WebDriverWait(driver, 30)
    driver.get('Link to the dashboard')
    wait.until(EC.element_to_be_clickable((By.XPATH, "//button[contains(.,'Download CSV')]"))).click()    

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM