Home > Enterprise >  how to download email attachment with selenium python?
how to download email attachment with selenium python?

Time:03-24

This is the html for the download part of the page:

<ul id="attachment-list" ><li  id="attach2"><a href="./?_task=mail&amp;_action=get&amp;_mbox=INBOX&amp;_uid=1&amp;_token=ukxOEh6bQm6Iv7gN59mROEbGpTrczta3&amp;_part=2" onclick="return rcmail.command('load-attachment','2',this)" onm ouseover="rcube_webmail.long_subject_title_ex(this, 0)" title="" ><span >2ART.xlsx</span><span >(~740 KB)</span></a><a href="#" tabindex="0" title="Opções" ><span >Opções</span></a></li>
</ul>

and I can't find any element related to the file.

driver.find_element(By.XPATH, '//*[@id="attach2"]/a[2]')

the output is:

Message: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id="attach2"]/a[2]"}

CodePudding user response:

Please check in the dev tools (Google chrome) if we have unique entry in HTML-DOM or not.

xpath that you should check :

//ul[@id='attachment-list']//li[@id='attach2']//a[@title='Opções']

Steps to check:

Press F12 in Chrome -> go to element section -> do a CTRL F -> then paste the xpath and see, if your desired element is getting highlighted with 1/1 matching node.

If it's a unique match then click it like below:

Code trial 1:

time.sleep(5)
driver.find_element(By.XPATH, "//ul[@id='attachment-list']//li[@id='attach2']//a[@title='Opções']").click()

Code trial 2:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@id='attachment-list']//li[@id='attach2']//a[@title='Opções']"))).click()

Imports:

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Code trial 2 is recommended.

if you still face the NoSuchElementException: with code trial 1 then debug like this:

If this is unique //ul[@id='attachment-list']//li[@id='attach2']//a[@title='Opções'] then you need to check for the below conditions as well.

  1. Check if it's in any iframe/frame/frameset.

    Solution: switch to iframe/frame/frameset first and then interact with this web element.

  2. Check if it's in any shadow-root.

    Solution: Use driver.execute_script('return document.querySelector to have returned a web element and then operates accordingly.

  3. If you have redirected to a new tab/ or new windows and you have not switched to that particular new tab/new window, otherwise you will likely get NoSuchElement exception.

    Solution: switch to the relevant window/tab first.

  4. If you have switched to an iframe and the new desired element is not in the same iframe context then first switch to default content and then interact with it.

    Solution: switch to default content and then switch to respective iframe.

  • Related