參考:教你兩種python selenium保存圖片的方法_Linux小百科的博客-CSDN博客_python selenium 保存圖片
優(yōu)點是可以繞過服務(wù)器的反爬蟲限制乾翔,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):
# 這里是調(diào)用入口
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