Python保存網頁圖片
這個是個比較簡單的例子,網頁中的圖片地址都是使用'http://。。。。.jpg'這種方式直接定義的。
使用前,可以先建立好一個文件夾用于保存圖片,本例子中使用的文件夾是 d:\\pythonPath這個文件夾
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
# -*- coding: UTF-8 -*- import os,re,urllib,uuid #首先定義云端的網頁,以及本地保存的文件夾地址 urlPath = 'http://gamebar.com/' localPath = 'd:\\pythonPath' #從一個網頁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()) #根據文件名創建文件 def createFileWithFileName(localPathParam,fileName): totalPath = localPathParam + '\\' + fileName if not os.path.exists(totalPath): file = open (totalPath, 'a+' ) file .close() return totalPath #根據圖片的地址,下載圖片并保存在本地 def getAndSaveImg(imgUrl): if ( len (imgUrl)! = 0 ): fileName = generateFileName() + '.jpg' urllib.urlretrieve(imgUrl,createFileWithFileName(localPath,fileName)) #下載函數 def downloadImg(url): urlList = getUrlList(url) for urlString in urlList: getAndSaveImg(urlString) downloadImg(urlPath) |
保存的文件如下:
網頁的一部分保存為圖片
主要思路是selenium+phantomjs(中文網頁需要設置字體)+PIL切圖
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
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) |