Python和愛好的結(jié)合。
今天是爬蟲姐姐
平時喜歡編織,遇到編織圖解會收藏起來。 遇到一個帖子,以圖片的方式上傳了一本編織書,整本書有80多張jpg圖片,姐姐喜歡這本書,但是一張張保存下來,有點(diǎn)麻煩,于是,爬蟲姐姐上線,爬下來吧。
一番查資料,讀文檔,看別人的代碼,終于搞出來了,分享代碼。 嘗試了兩種方式,urllib.request包 和requests包,均成功。 相比較,requests兼容性以及簡潔性更有優(yōu)勢。
上代碼:
#-*- coding:utf-8 -*-
import urllib.request
import re,os
import urllib
from urllib.error import HTTPError
import requests
#根據(jù)給定的網(wǎng)址來獲取網(wǎng)頁詳細(xì)信息,得到的html就是網(wǎng)頁的源代碼
def getHtml(url):
'''
#使用urllib.request
page = urllib.request.urlopen(url)
html = page.read()
return html.decode('gb18030')
'''
#使用requests
response = requests.get(url)
return response.text
#獲取網(wǎng)頁所有圖片的URL列表
def getImgList(html):
reg = r'src="(.+?\.jpg)"'
imgre = re.compile(reg)
imglist = imgre.findall(html)#表示在整個網(wǎng)頁中過濾出所有圖片的地址,放在imglist中
return imglist
#下載圖片
def getImg(html,imgSavepath):
imglist = getImgList(html)
i = 0
for imgurl in imglist:
#print(imgurl)
try:
#使用urllib.request
#urllib.request.urlretrieve(imgurl,'{}{}.jpg'.format(imgSavepath,i)) #打開imglist中保存的圖片網(wǎng)址,并下載圖片保存在本地,format格式化字符串
# 使用requests
imgres = requests.get(imgurl)
img = imgres.content
with open(imgSavepath+str(i)+'.jpg', 'wb') as f:
f.write(img)
f.close()
#end requests
i = i + 1
except HTTPError as e: # urllib.request 方式找不到圖片會報HTTPError 404, requests方式不會
print (e.reason)
return i
def main():
print ("start")
html = getHtml("http://www.bianzhile.com/p/20222") #獲取該網(wǎng)址網(wǎng)頁詳細(xì)信息,得到的html就是網(wǎng)頁的源代碼
#將圖片保存到D:\\test\\文件夾中,如果沒有test文件夾則創(chuàng)建
imgSavePath = 'D:\\test\\'
if not os.path.isdir(imgSavePath):
os.makedirs(imgSavePath)
else:
print (imgSavePath)
picNum = getImg(html,imgSavePath) #從網(wǎng)頁源代碼中分析并下載保存圖片
print ("save %d pictureses"%picNum)
if __name__ == "__main__":
main()