使用Python保存網(wǎng)頁上的圖片或者保存頁面為截圖
Python保存網(wǎng)頁圖片
這個(gè)是個(gè)比較簡(jiǎn)單的例子,網(wǎng)頁中的圖片地址都是使用'http://。。。。.jpg'這種方式直接定義的。
使用前,可以先建立好一個(gè)文件夾用于保存圖片,本例子中使用的文件夾是 d:\\pythonPath這個(gè)文件夾
代碼如下:
# -*- coding: UTF-8 -*-
import os,re,urllib,uuid
#首先定義云端的網(wǎng)頁,以及本地保存的文件夾地址
urlPath='http://gamebar.com/'
localPath='d:\\pythonPath'
#從一個(gè)網(wǎng)頁url中獲取圖片的地址,保存在
#一個(gè)list中返回
def getUrlList(urlParam):
urlStream=urllib.urlopen(urlParam)
htmlString=urlStream.read()
if( len(htmlString)!=0 ):
patternString=r'http://.{0,50}\.jpg'
searchPattern=re.compile(patternString)
imgUrlList=searchPattern.findall(htmlString)
return imgUrlList
#生成一個(gè)文件名字符串
def generateFileName():
return str(uuid.uuid1())
#根據(jù)文件名創(chuàng)建文件
def createFileWithFileName(localPathParam,fileName):
totalPath=localPathParam+'\\'+fileName
if not os.path.exists(totalPath):
file=open(totalPath,'a+')
file.close()
return totalPath
#根據(jù)圖片的地址,下載圖片并保存在本地
def getAndSaveImg(imgUrl):
if( len(imgUrl)!= 0 ):
fileName=generateFileName()+'.jpg'
urllib.urlretrieve(imgUrl,createFileWithFileName(localPath,fileName))
#下載函數(shù)
def downloadImg(url):
urlList=getUrlList(url)
for urlString in urlList:
getAndSaveImg(urlString)
downloadImg(urlPath)
保存的文件如下:

網(wǎng)頁的一部分保存為圖片
主要思路是selenium+phantomjs(中文網(wǎng)頁需要設(shè)置字體)+PIL切圖
def webscreen():
url = 'http://www.xxx.com'
driver = webdriver.PhantomJS()
driver.set_page_load_timeout(300)
driver.set_window_size(1280,800)
driver.get(url)
imgelement = driver.find_element_by_id('XXXX')
location = imgelement.location
size = imgelement.size
savepath = r'XXXX.png'
driver.save_screenshot(savepath)
im = Image.open(savepath)
left = location['x']
top = location['y']
right = left + size['width']
bottom = location['y'] + size['height']
im = im.crop((left,top,right,bottom))
im.save(savepath)
相關(guān)文章
python 如何在list中找Topk的數(shù)值和索引
這篇文章主要介紹了python 如何在list中找Topk的數(shù)值和索引的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-05-05
Django博客系統(tǒng)注冊(cè)之創(chuàng)建用戶模塊應(yīng)用
本文主要介紹了Django博客系統(tǒng)注冊(cè)之創(chuàng)建用戶模塊應(yīng)用,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
python中讀入二維csv格式的表格方法詳解(以元組/列表形式表示)
Python二叉樹的鏡像轉(zhuǎn)換實(shí)現(xiàn)方法示例
Python創(chuàng)建模塊及模塊導(dǎo)入的方法

