今天学习Python爬虫简单的实例。爬取好看的汽车图片并保存到我的电脑。话不多说,直接上代码:
import urllib.request
import re
import chardet
def getHtml(url):
page = urllib.request.urlopen(url)
html = page.read()
return html
def getImg(html):
global i
reg = 'src="(.+?\.jpg)" alt='
imgre = re.compile(reg)
encode_type = chardet.detect(html)
html = html.decode(encode_type['encoding'])
imglist = re.findall(imgre, html)
x = 0
i=0
for imgurl in imglist:
urllib.request.urlretrieve(imgurl, '%s.jpg' % x)
x+=1
i+=1
return imglist
html = getHtml("http://news.bitauto.com/duochedaogou/20180512/1807398072.html")
print (getImg(html))
print('总共处理了 %s 张图片'%(i))
程序运行结果:如图示:
共保存了13张图片;如图所示:
注意图片是保存在PY文件所在的目录。
知识点:
1、chardet的安装。应该把下载的chardet文件解压到C:\Python34\Scripts目录下然后再安装。否则有时会不识别。
2、python2.7与python3. x urllib模块导入方法及使用方法的不同。
3、正则表达式的学习是正确解析URL的关键。