Issue
I found out in Web Inspector tool image on one site (domain is just for example)
https://somesite.com/asd/photo.pl?num=10 which is not part of website but is probably generated dynamically from server.
I would like to ask if is possible to download it via selenium in python.
I tried this but it does not works. I think it is not possible by this way due to server site like I meantioned.
from selenium import webdriver
import urllib.request
import shutil
import time
import requests
driver = webdriver.Firefox()
driver.get("https://somesite.com/")
img = driver.find_element(By.XPATH, '/html/body/div[2]/div/div[1]/a/img')
img_url = img.get_attribute('src')
response = requests.get(img_url)
with open("saved_image.jpg", "wb") as file:
file.write(response.content)
Solution
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
# Setup WebDriver
driver = webdriver.Firefox()
driver.get("https://somesite.com/")
# Wait for the image to be loaded
wait = WebDriverWait(driver, 10)
img = wait.until(EC.presence_of_element_located((By.XPATH, '/html/body/div[2]/div/div[1]/a/img')))
# Get image URL
img_url = img.get_attribute('src')
# Download the image using Selenium
driver.get(img_url)
time.sleep(2) # Wait for the image to load
# Save the image
with open("saved_image.jpg", "wb") as file:
file.write(driver.find_element(By.TAG_NAME, "img").screenshot_as_png)
# Clean up
driver.quit()
This script uses Selenium to navigate to the image URL and then saves the image using Selenium's screenshot functionality. It ensures the image is loaded before saving and doesn't mix Selenium with requests, which can be helpful if the image requires a valid session or specific cookies to be accessed.
Answered By - NoneSecNetSer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.