Hani Gotc
Hani Gotc

Reputation: 890

Cannot open new tab for selenium in order to download a CSV file python

Problem description

I am working on ubuntu 16.04. I want to download CSV files from a website. They are presented by links. The moment I click on the link I want to open a new tab which will download the file. I used the solution provided in https://gist.github.com/lrhache/7686903.

 image description here


setup

 fp = webdriver.FirefoxProfile()
    fp.set_preference("browser.download.folderList",2)
    fp.set_preference("browser.download.manager.showWhenStarting",False)
    fp.set_preference("browser.download.dir",download_path)
    fp.set_preference("browser.helperApps.neverAsk.saveToDisk","text/csv")

    # create a selenium webdriver
    browser = webdriver.Firefox(firefox_profile=fp)
    # open QL2 website
    browser.get('http://live.ql2.com')

code

 csvList = browser.find_elements_by_class_name("csv")
    for l in csvlist:
           if 'error' not in l.text and 'after' not in l.text:
               l.send_keys(Keys.CONTROL +'t')
    

Every Element l is represented as follows:

<selenium.webdriver.firefox.webelement.FirefoxWebElement (session="9003fc6a-d8be-472b-bced-94fffdb5fdbe", element="27e1638a-0e37-411d-8d30-896c15711b49")>

Question

Why am I not able to open a new tab. Is there something missing?

Upvotes: 0

Views: 375

Answers (1)

Brydenr
Brydenr

Reputation: 798

The problem seems to be that you are just making a new tab, not opening the link in a new tab.

Try using ActionChains:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

# create browser as detailed in OP's setup
key_code = Keys.CONTROL
csvList = browser.find_elements_by_class_name("csv")
for l in csvlist:
    if 'error' not in l.text and 'after' not in l.text:
        actions = webdriver.ActionChains(browser)
        # Holds down the key specified in key_code
        actions.key_down(key_code)
        # Clicks the link
        actions.click(l)
        # Releases down the key specified in key_code
        actions.key_up(key_code)
        # Performs the actions specified in the ActionChain
        actions.perform()

Upvotes: 1

Related Questions