SoFunction
Updated on 2024-11-19

Using Python to save an image on a web page or save a page as a screenshot

Python Save Web Image
This is a relatively simple example of a web page where the image addresses are defined using 'http://。。。。 .jpg' which is defined directly.

Before you use it, you can create a folder to save the image, in this example, the folder is d:\\\pythonPath.

The code is as follows:

# -*- coding: UTF-8 -*- 
import os,re,urllib,uuid 
 
# First define the web page in the cloud, and the address of the locally saved folder
urlPath='/' 
localPath='d:\\pythonPath' 
 
 
# Get the address of an image from a web page url, save it in the
#Returns a list of
def getUrlList(urlParam): 
  urlStream=(urlParam) 
  htmlString=() 
  if( len(htmlString)!=0 ): 
    patternString=r'http://.{0,50}\.jpg' 
    searchPattern=(patternString) 
    imgUrlList=(htmlString) 
    return imgUrlList 
 
     
# Generate a filename string
def generateFileName(): 
  return str(uuid.uuid1()) 
 
   
# Create files based on filenames
def createFileWithFileName(localPathParam,fileName): 
  totalPath=localPathParam+'\\'+fileName 
  if not (totalPath): 
    file=open(totalPath,'a+') 
    () 
    return totalPath 
   
 
#Download the image and save it locally based on the address of the image
def getAndSaveImg(imgUrl): 
  if( len(imgUrl)!= 0 ): 
    fileName=generateFileName()+'.jpg' 
    (imgUrl,createFileWithFileName(localPath,fileName)) 
 
 
#Download Functions
def downloadImg(url): 
  urlList=getUrlList(url) 
  for urlString in urlList: 
    getAndSaveImg(urlString) 
     
downloadImg(urlPath) 

The saved files are as follows:

 (755×329)


Saving part of a web page as an image
The main idea is selenium + phantomjs (Chinese web pages need to set the font) + PIL cut map

def webscreen():
  url = ''
  driver = ()
  driver.set_page_load_timeout(300)
  driver.set_window_size(1280,800)
  (url)
  imgelement = driver.find_element_by_id('XXXX')
  location = 
  size = 
  savepath = r''
  driver.save_screenshot(savepath)
  im = (savepath)
  left = location['x']
  top = location['y']
  right = left + size['width']
  bottom = location['y'] + size['height']
  im = ((left,top,right,bottom))
  (savepath)