参考:教你两种python selenium保存图片的方法_Linux小百科的博客-CSDN博客_python selenium 保存图片
优点是可以绕过服务器的反爬虫限制,requests无法下载图片的时候可以使用。
import os
import requests
from seleniumwire import webdriver
import base64
import os
import re
from io import BytesIO
from PIL import Image
def base64_to_image(base64_str):
base64_data = re.sub('^data:image/.+;base64,', '', base64_str)
byte_data = base64.b64decode(base64_data)
image_data = BytesIO(byte_data)
img = Image.open(image_data)
return img
js = "let c = document.createElement('canvas');let ctx = c.getContext('2d');" \
"let img = document.getElementsByTagName('img')[0]; /*找到图片*/ " \
"c.height=img.naturalHeight;c.width=img.naturalWidth;" \
"ctx.drawImage(img, 0, 0,img.naturalWidth, img.naturalHeight);" \
"let base64String = c.toDataURL();return base64String;"
def se_down(file_path, picture_url):
# 这里是调用入口
browser.get(picture_url)
base64_str = browser.execute_script(js)
img = base64_to_image(base64_str)
img = img.convert('RGB')
img.save(file_path)
browser = webdriver.Edge(seleniumwire_options={'port': 12345})
if __name__ == "__main__":
pass