brfh
brfh

Reputation: 344

How to get download link to the file, in the firefox downloads via selenium and python3

I can't get link in webpage, it's generat automaticly using JS. But I can get firefox download window after clicking on href (it's a JS script, that returns href).

How can I get the link in this window using selenium. If i can't do this, is there any other way to get link (no explicit link in the HTML DOM)

Upvotes: 1

Views: 1022

Answers (2)

Shubham Jain
Shubham Jain

Reputation: 17553

from selenium import webdriver

profile = webdriver.FirefoxProfile()
profile.set_preference('browser.download.folderList', 2) # 2 means custom location
profile.set_preference('browser.download.manager.showWhenStarting', False)
profile.set_preference('browser.download.dir', '/tmp') # location is tmp
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', 'text/csv')

browser = webdriver.Firefox(profile)
browser.get("yourwebsite")

element = browser.find_element_by_id('yourLocator')
href = element.get_attribute("href")

Now you have website in your href.

Use below code to navigate to the URL

browser.navigate().to(href)

Upvotes: 1

Dmitri T
Dmitri T

Reputation: 168072

You can go for the following approach:

  1. Get WebElement's href attribute using WebElement.get_attribute() function

    href = your_element.get_attribute("href")
    
  2. Use WebDriver.execute_script() function to evaluate the JavaScript and return the real URL

    url = driver.execute_script("return " + href + ";")
    
  3. Now you should be able to use urllib or requests library to download the file. If your website assumes authentication - don't forget to obtain Cookies from the browser instance and add the relevant Cookie header to the request downloading the file

Upvotes: 0

Related Questions