您的位置:首页 > 编程语言 > Python开发

Python3 爬虫下载指定页面图片

2016-09-05 11:57 567 查看
Python3.X

#coding=utf8
import re
import urllib.request

def getHtml(url):
page = urllib.request.urlopen(url)
html = page.read().decode('latin-1').encode('utf-8').decode('utf-8')
#html = page.read()
#html = html.decode('gbk')
page.close()
return html

def getImg(html):
reg = r'src="(.*?\.jpg)" width'
imgre = re.compile(reg)
imglist = re.findall(imgre, html)
n = 0
for imgurl in imglist:
if 'http' in imgurl:
print(imgurl)
urllib.request.urlretrieve(imgurl, '%s.jpg' % n)
n += 1

html = getHtml('http://www.123.com/index.html')
getImg(html)


Python2.X

#coding=utf8
import re
import urllib

def getHtml(url):
page = urllib.urlopen(url) #获取的是一个页面对象
html = page.read()          #读取出来的是html代码
return html

def getImg(html):
reg = r'src="(.*?\.jpg)" width'
imgre = re.compile(reg)            #编译是为了让正则执行得更快
imglist = re.findall(imgre,html)
n = 0
for imgurl in imglist:
if 'http' in imgurl:
print(imgurl)
urllib.urlretrieve(imgurl,'%s.jpg' % n)
n += 1

html = getHtml('http://www.efeihu.com/sale/index_new.html')
getImg(html)



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: