Ger Cas
Ger Cas

Reputation: 2298

Determine all download links in page, then download all files

I want to download all files in a site. All files have a link with text = "Download" and given click on it downloads each file.

The html of each file is like this:

<a abc-id="0" href="#" class="todown" nc="0">Download</a>

In XPath of each file the only value that changes is tr number like this:

    //*[@id='dwn']/div/table[1]/tbody[1]/tr[1]/td[3]/a
    //*[@id='dwn']/div/table[1]/tbody[1]/tr[2]/td[3]/a
    .
    .
    .
    //*[@id='dwn']/div/table[1]/tbody[1]/tr[100]/td[3]/a        

My current code is below that works but I have several time.sleep() and ...click() commands, one for each file:

import time
from selenium import webdriver

driver = webdriver.Chrome("C:\webdrivers\chromedriver.exe")

driver.get ("http://www.examplesite.com/")
time.sleep(3)
driver.find_element_by_xpath("//*[@id='dwn']/div/table[1]/tbody[1]/tr[1]/td[3]/a").click()
time.sleep(3)
driver.find_element_by_xpath("//*[@id='dwn']/div/table[1]/tbody[1]/tr[2]/td[3]/a").click()
.
.
.
time.sleep(3)
driver.find_element_by_xpath("//*[@id='dwn']/div/table[1]/tbody[1]/tr[100]/td[3]/a").click()

May someone help me in how to download all files in page with a kind of loop, since the number of files is not always the same.

Thanks in advance

Upvotes: 0

Views: 105

Answers (2)

Surajit Mitra
Surajit Mitra

Reputation: 414

With respect to your given code, if only changing value is TR, then you can loop through all the TR tags by increasing it's loop counter value.

from time import sleep
from selenium import webdriver

driver = webdriver.Chrome("C:\webdrivers\chromedriver.exe")

driver.get ("http://www.examplesite.com/")
time.sleep(3)
length_of_tr = 100
for i in range(1,length_of_tr):
    driver.find_element_by_xpath("//*[@id='dwn']/div/table[1]/tbody[1]/tr["+str(i)+"]/td[3]/a").click()
    sleep(3)

you can decide how you can define length of tr. You can get the length of tr tags dynamically while running the code or you can define a range inside the code as well.

Upvotes: 1

Ranjitha
Ranjitha

Reputation: 49

findElements() method can be used to get all file links in a list.

List<WebElement> l=driver.findElements(By.linkText("Download"));
for(int i=0;i<l.size();i++)
{
l.get(i).click();
}

Try using this logic.

Upvotes: 0

Related Questions