URL ์์ฒญ ๋ฐฉ์์ธ urllib.urlretrieve์ src ์ฃผ์๋ก ์์ฒญ์ ํ๋ ๋ฐฉ์์ด๊ธฐ ๋๋ฌธ์ ์บก์ฑ (์๋๋ฑ๋ก๋ฐฉ์ง ๋ฌธ์)์ฒ๋ผ ๋งค๋ฒ ์์ฒญํ ๋๋ง๋ค ์ด๋ฏธ์ง๊ฐ ๋ฐ๋๋ ๊ฒฝ์ฐ๊ฐ ์์ด ๋ฌด์ฉ์ง๋ฌผ์ด ๋๋ค. ๊ทธ๋ฌ๋ฏ๋ก ์ด๋ฏธ ๋ธ๋ผ์ฐ์ ์ ๋ก๋๊ฐ ๋ ์ด๋ฏธ์ง๋ฅผ ๊ฐ์ ธ์ค๋ ๋ฐฉ๋ฒ์ ์ฌ์ฉํด์ผ ํ๋ค.
๋ฐฉ๋ฒ 1. screenshot_as_png ์ฌ์ฉ (์ถ์ฒ)
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('https://www.webpagetest.org/')
with open('filename.png', 'wb') as file:
file.write(driver.find_element_by_xpath('/html/body/div[1]/div[5]/div[2]/table[1]/tbody/tr/td[1]/a/div').screenshot_as_png)
๋ฐฉ๋ฒ 2. ์๋ฐ์คํฌ๋ฆฝํธ ์ฌ์ฉ (PIL ๋ชจ๋์ Image ํจ์๋ก ์ ์ฅ)
from io import BytesIO
from PIL import Image
from base64 import b64decode
driver.get(url)
# Create a canvas, set it's width and height equal to image's
# Write image to canvas, translate to base64
# Remove metadata prefix
b64img = driver.execute_script(r'''
var img = document.getElementsByTagName("img")[0];
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
''')
# Decode from base64, translate to bytes and write to PIL image
img = Image.open(BytesIO(b64decode(b64img)))
img.save("./filename.png")
๋ฐฉ๋ฒ 3. ์๋ฐ์คํฌ๋ฆฝํธ ์ฌ์ฉ (ํ์ผ ์ ์ถ๋ ฅ์ผ๋ก ์ ์ฅ)
from io import BytesIO
from base64 import b64decode
driver.get(url)
# Create a canvas, set it's width and height equal to image's
# Write image to canvas, translate to base64
# Remove metadata prefix
b64img = driver.execute_script(r'''
var img = document.getElementsByTagName("img")[0];
var canvas = document.createElement("canvas");
canvas.width = img.width;
canvas.height = img.height;
var ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0);
var dataURL = canvas.toDataURL("image/png");
return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
''')
imgdata = base64.b64decode(b64img)
filename = 'filename.png' # I assume you have a way of picking unique filenames
with open(filename, 'wb') as f:
f.write(imgdata)
์ถ์ฒ:
https://stackoverflow.com/questions/17361742/download-image-with-selenium-python
Download image with selenium python
I want get captcha image from browser. I have got a url of this picture, but the this picture changes each updated time (url is constant). Is there any solution to get picture from browser (like '...
stackoverflow.com
https://stackoverflow.com/questions/16214190/how-to-convert-base64-string-to-image
How to convert base64 string to image?
I'm converting an image to base64 string and sending it from android device to the server. Now, I need to change that string back to an image and save it in the database. Any help?
stackoverflow.com