简体   繁体   中英

How can I download a image on a click event using selenium?

I want to download the image at this site https://imginn.com/p/CXVmwujLqbV/ via the button. but i always fail. this is the code i use.

driver.find_element_by_xpath('/html/body/div[2]/div[5]/a').click()

Well, Check this post for downloading resource. Picture has 'src' attribute in 'img' tag, that holds it.

Also, (though it just might be simplification just for this question), do not hardcode your xpath. Learn to code nicely using "Page Object Pattern".

There are several possible problems here:

  1. You need to add a delay / wait before accessing this element.
  2. You have to scroll the page since the element you wish to click is initially out of the view.
  3. You should improve you locator. It's highly NOT recommended to use absolute XPaths.
    This should work:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
import time

driver = webdriver.Chrome(executable_path='chromedriver.exe')

wait = WebDriverWait(driver, 20)
actions = ActionChains(driver)

driver.get("https://imginn.com/p/CXVmwujLqbV/")

button = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, "div.downloads a")))
time.sleep(0.5)
actions.move_to_element(button).perform()
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.downloads a"))).click()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM