chris
chris

Reputation: 148

Unable to click on the download link with js backend

There is a link on a website that downloads a csv file. The link is in a table but the actual download link is hidden.

<div id="testjs">
    <div test-example="">
        <table test-example="">
            <tr test-example="">
                <th test-example="">Car</th>
                <th test-example="">File</th>
            </tr>
            <tr test-example="">
                <td test-example="">Ford</td>
                <td test-example="">
                    <a test-example="" href="#">ford.csv</a>
                </td>
            </tr>
        </table>
    </div>
</div>

I'm trying automate file download by scraping the site using python/selenium.

from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get("https://www.example.com")
driver.find_element_by_link_text('ford.csv')

When the last line above runs the script returns:

<selenium.webdriver.remote.webelement.WebElement (session="<example session string>", element="<example element string>")>

When I run the code below nothing happens:

driver.find_element_by_link_text('ford.csv').click()

How do I get the file to download?

Upvotes: 1

Views: 389

Answers (2)

undetected Selenium
undetected Selenium

Reputation: 193088

Apparently there isn't any issue with the following line of code:

driver.find_element_by_link_text('ford.csv')

However at this point it is worth to mention that the dot character . always have a special effect/meaning.


Assuming you intend to click() on the element with text as ford.csv which is adjacent to the element with text as Ford, as a solution you can:

  • Split the text ford.csv into two parts ford and csv and use within a
  • As you intent to invoke click(), you have to induce WebDriverWait for the element_to_be_clickable()
  • You can use either of the following Locator Strategies:

    • Using CSS_SELECTOR:

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "tr[test-example] td:nth-child(2)>a[test-example]"))).click()
      
    • Using XPATH:

      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(., 'ford') and contains(.,'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
      

Upvotes: 1

Wonka
Wonka

Reputation: 1886

PhantomJS is not supported in new Selenium version, consider user other driver. For your problem there were a bug clicking Button with JS.

Try this, I found in my selenium library to click_js buttons

item = driver.find_element_by_link_text('ford.csv')
ActionChains(driver).move_to_element(item).click().perform()

Upvotes: 0

Related Questions