普遍情况下都是先获取图片链接后使用requests+open或者urllib进行下载,但有时候遇到反爬就无法下载,就可以使用selenium进行下载。
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("图片链接")
1.利用selenium截图
注: 该方法缺点在于是整个页面截图,会把图片的黑边都截取出来
driver.save_screenshot('screenshot.jpg')
2.利用selenium定位元素截图
引自:https://stackoverflow.com/questions/17361742/download-image-with-selenium-python
方式一:
with open('a.png', 'wb') as file:
file.write(driver.find_element_by_xpath('//body/img[1]').screenshot_as_jpg)
方式二(推荐,简洁方便):
driver.find_element_by_xpath('//body/img[1]').screenshot("a.jpg")
3.模拟鼠标右键另存为
引自:https://blog.csdn.net/freesigefei/article/details/52213017
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
element = driver.find_element_by_xpath('//body/img[1]')
action = ActionChains(driver).move_to_element(element) # 移动到该元素
action.context_click(element).perform() # 右键点击该元素
action.send_keys(Keys.ARROW_DOWN).perform() # 点击键盘向下箭头
action.send_keys('v').perform() # 键盘输入V保存图
action.perform() # 执行保存
文章来源:https://blog.csdn.net/qq_37267676/article/details/111667266