利用selenium下载图片,不使用requests和urllib等其他工具

通常获取图片链接后用requests+open或urllib下载,遇反爬时可使用selenium。介绍了利用selenium的三种下载图片方式,包括整个页面截图、定位元素截图(推荐简洁方式)以及模拟鼠标右键另存为,并给出相关参考链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

普遍情况下都是先获取图片链接后使用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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值