'Python selenium clicking a button
I am trying to write a python script to automatically download csv using the "Download CSV" button from the below link: https://chartink.com/screener/copy-supertrend-negative-breakout-1103
from selenium import webdriver
import pandas as pd
DRIVER_PATH = r"C:\Users\u123456\Downloads\chromedriver\chromedriver.exe"
d = webdriver.Chrome(executable_path=DRIVER_PATH)
d.get('https://chartink.com/screener/copy-supertrend-negative-breakout-1103')
download_button = pd.read_html(d.find_element_by_class_name('btn btn-default buttons-excel buttons-html5 btn-primary'))[0]
#table = pd.read_html(d.find_element_by_id('DataTables_Table_0').get_attribute('outerHTML'))[0]
print(download_button)
I am not finding any clue on how to click that button and download it to local drive. Any help would be highly appreciated.
Edit: I tried the below code and got it working, Now I would like to know if we can find the filename and load it into pandas dataframe.
element = d.find_element_by_link_text("Download csv")
element.click()
Thanks, mc
Solution 1:[1]
To click on the element Download csv you can use either of the following Locator Strategies:
Using
link_text
:driver.find_element_by_link_text("Download csv").click()
Using
css_selector
:driver.find_element_by_css_selector("a.btn.btn-default.buttons-excel.buttons-html5.btn-primary[value='Download backtest']").click()
Using
xpath
:driver.find_element_by_xpath("//a[@value='Download backtest' and text()='Download csv']").click()
Ideally, to click on the element you need to induce WebDriverWait for the element_to_be_clickable()
and you can use either of the following Locator Strategies:
Using
LINK_TEXT
:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Download csv"))).click()
Using
CSS_SELECTOR
:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.btn.btn-default.buttons-excel.buttons-html5.btn-primary[value='Download backtest']"))).click()
Using
XPATH
:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@value='Download backtest' and text()='Download csv']"))).click()
Note: You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | undetected Selenium |