使用Python保存網(wǎng)頁上的圖片或者保存頁面為截圖
更新時間:2016年03月05日 14:47:28 作者:j_akill
這篇文章主要介紹了使用Python保存網(wǎng)頁上的圖片或者保存頁面為截圖的方法,保存網(wǎng)頁圖片主要用到urllib模塊,即簡單的爬蟲原理,需要的朋友可以參考下
Python保存網(wǎng)頁圖片
這個是個比較簡單的例子,網(wǎng)頁中的圖片地址都是使用'http://。。。。.jpg'這種方式直接定義的。
使用前,可以先建立好一個文件夾用于保存圖片,本例子中使用的文件夾是 d:\\pythonPath這個文件夾
代碼如下:
# -*- coding: UTF-8 -*-
import os,re,urllib,uuid
#首先定義云端的網(wǎng)頁,以及本地保存的文件夾地址
urlPath='http://gamebar.com/'
localPath='d:\\pythonPath'
#從一個網(wǎng)頁url中獲取圖片的地址,保存在
#一個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
#生成一個文件名字符串
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二叉樹的鏡像轉(zhuǎn)換實現(xiàn)方法示例
這篇文章主要介紹了Python二叉樹的鏡像轉(zhuǎn)換實現(xiàn)方法,結(jié)合實例形式分析了二叉樹鏡像轉(zhuǎn)換的原理及Python相關(guān)算法實現(xiàn)技巧,需要的朋友可以參考下2019-03-03
Python中八種數(shù)據(jù)導(dǎo)入方法總結(jié)
數(shù)據(jù)分析過程中,需要對獲取到的數(shù)據(jù)進(jìn)行分析,往往第一步就是導(dǎo)入數(shù)據(jù)。導(dǎo)入數(shù)據(jù)有很多方式,不同的數(shù)據(jù)文件需要用到不同的導(dǎo)入方式,相同的文件也會有幾種不同的導(dǎo)入方式。下面總結(jié)幾種常用的文件導(dǎo)入方法2022-11-11

