Home > OS >  How to click the button via Selenium with 'onclick' info only?
How to click the button via Selenium with 'onclick' info only?

Time:02-17

The only thing html has with the button is:

<button onclick="exportTableToCSV('hahaha.csv')">export as csv</button>

No class or id or name or type.
Tried with xpath and link text, neither works.

browser.find_element_by_xpath("//button[onclick=\"exportTableToCSV('hahaha.csv')\"]").click()
browser.find_element_by_link_text("export as csv").click()

Both return to error:

Message: no such element: Unable to locate element: {"method":"xpath","selector":"//button[onclick="exportTableToCSV('hahaha.csv')"]"}

Message: no such element: Unable to locate element: {"method":"link text","selector":"export as csv"}

Help appreciated!!!

CodePudding user response:

You can locate this element with XPath or CSS Selector.
The locator you tried has some syntax error.
Please try this XPath:

browser.find_element_by_xpath("//button[@onclick=\"exportTableToCSV('hahaha.csv')\"]").click()

Or this CSS Selector

browser.find_element_by_css_selector("button[onclick=\"exportTableToCSV('hahaha.csv')\"]").click()

In case exportTableToCSV is an unique value you can also use this XPath

browser.find_element_by_xpath("//button[contains(@onclick,'exportTableToCSV')]").click()

CodePudding user response:

The text export as csv is the text of the <button> element but not of an <a> tag. Hence you can't use find_element_by_link_text() to locate the desired element.


Solution

To click() on a element with text as export as csv you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:

  • Using CSS_SELECTOR:

    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[onclick^='exportTableToCSV']"))).click()
    
  • Using XPATH:

    WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[starts-with(@onclick, 'exportTableToCSV') and text()='export as 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
    
  • Related