简体   繁体   English

如何使用 selenium 在点击事件上下载图像?

[英]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.我想通过按钮在此站点https://imginn.com/p/CXVmwujLqbV/下载图像。 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.图片在“img”标签中具有“src”属性,它包含它。

Also, (though it just might be simplification just for this question), do not hardcode your xpath.另外,(尽管它可能只是为了这个问题而简化),不要对你的 xpath 进行硬编码。 Learn to code nicely using "Page Object Pattern".学习使用“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.强烈不建议使用绝对 XPath。
    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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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