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

【Python】python3实现网页爬虫下载图片

2017-11-02 13:36 811 查看
import re
import urllib.request

# ------ 获取网页源代码的方法 ---
def getHtml(url):
page = urllib.request.urlopen(url)
html = page.read()
return html

# ------ getHtml()内输入任意帖子的URL ------
html = getHtml("https://tieba.baidu.com/p/5352556650")
# ------ 修改html对象内的字符编码为UTF-8 ------
html = html.decode('UTF-8')

# ------ 获取帖子内所有图片地址的方法 ------
def getImg(html):
# ------ 利用正则表达式匹配网页内容找到图片地址 ------
reg = r'src="([.*\S]*\.jpg)"'
imgre = re.compile(reg);
imglist = re.findall(imgre, html)
return imglist

imgList = getImg(html)
imgName = 0
for imgPath in imgList:
# ------ 这里最好使用异常处理及多线程编程方式 ------
try:
f = open('D:\\Temp\\'+ str(imgName)+".jpg", 'wb')
f.write((urllib.request.urlopen(imgPath)).read())
print(imgPath)
f.close()
except Exception as e:
print(imgPath+" error")
imgName += 1

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