干货必看 | Python爬虫爬取网络图片

在这里插入图片描述
今天教大家用爬虫抓取网络图片,以百度首页图片为例,爬取图片并保存到本地。
整体代码:
#coding=utf-8
#version: python 2.7
#author: Hao Chen

import urllib
import re

#step1.获取整个页面的数据
url=“http://image.baidu.com/”
page = urllib.urlopen(url) #打开一个url地址
html = page.read() #读取url上的数据

#step2.删选页面中想要的数据
reg = r’src="(.+?.jpg)" ’ #构建正则表达式
imgre = re.compile(reg) #把正则表达式变异成一个对象
imgList = re.findall(imgre,html) #读取html中包含正则表达式的数据

#直接用以下方法也行,更简便
#imgList = re.findall('src="(.+?.jpg)" ',html)

#step3.将页面筛选的数据保存到本地
x=0
for imgurl in imgList:
urllib.urlretrieve(imgurl,’%s.jpg’%x) #远程将数据下载到本地
x+=1

以上就是具体实现步骤。
文章部分内容源于网络,联系侵删*
文章参考源于http://h.zhimaruanjian.com/use/54912.html

猜你喜欢

转载自blog.csdn.net/zhimaHTTP/article/details/112028033