Anonymous
Anonymous

Reputation: 699

Download files inside div element using selenium - Python

I would like to use selenium in python to download files inside div element(no of files are dynamic inside div).I have a list of file names.

HTML Contents:

<div _ngcontent-c16="" class="ng-star-inserted">
<!---->
<!---->
    <div _ngcontent-c16="" class="documents ng-star-inserted">
        <div _ngcontent-c16="" class="row">
            <div _ngcontent-c16="" class="col-12">
            <button _ngcontent-c16="" class="btn btn-primary btn-block card-button" type="button" aria-describedby="cdk-describedby-message-2" cdk-describedby-host="" style="touch-action: none; user-select: none; -webkit-user-drag: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0);">
            <span _ngcontent-c16="" class="halflings halflings-download-alt">
            </span> example.zip 
            </button>
            </div>
        </div>
    </div>
    <div _ngcontent-c16="" class="documents ng-star-inserted">
        <div _ngcontent-c16="" class="row">
            <div _ngcontent-c16="" class="col-12">
            <button _ngcontent-c16="" class="btn btn-primary btn-block card-button" type="button" aria-describedby="cdk-describedby-message-2" cdk-describedby-host="" style="touch-action: none; user-select: none; -webkit-user-drag: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0);">
            <span _ngcontent-c16="" class="halflings halflings-download-alt">
            </span> example2.zip 
            </button>
            </div>
        </div>
    </div>
</div>

I am tried using...

xpath = "/html/body/app-root/div/mat-sidenav-container/mat-sidenav-content/div/div/app-application-detail/div/div/div[1]/div[2]/div[4]/div/div/div[2]/div/div/div/div/button"
driver.find_element_by_xpath(xpath).click()

I am tried using file name, xpath but not able to click and download file. Any solution ?

Upvotes: 0

Views: 537

Answers (1)

CEH
CEH

Reputation: 5909

Based on your HTML sample, it looks like the example.zip text is contained in the button element itself. Because there are multiple buttons, you should query on the example.zip text for the button. I would invoke a WebDriverWait and use a relative XPath like this:

button = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'example.zip')]")))
button.click()

If that does not work, you could try running Javascript to click the button instead:

button = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.XPATH, "//button[contains(text(), 'example.zip')]")))

driver.execute_script("arguments[0].click();", button)

Upvotes: 1

Related Questions