用Python抓取网页上的图片

试玩Python

目标:下载某个网页上的图片,保存到本地文件

工具:Python3.6和 Python2.7

一、试运行

一开始安装的是Python3.6版本

配置环境变量,在Path路径上加入Python的路径,然后在控制台输入Python -v,出现版本即可

在IDLE编辑器上输入简单的程序试试

1、先新建一个文件




2、然后在编辑框里输入

print ("hello world")

3、保存文件。

注意:文件名的后缀是 “.py”

4、按F5运行程序

结果如图表示完成

二、保存某个网页的图片到本地文件夹中

1、先说明一下,Python语言中“严格缩进”,“严格缩进”,“严格缩进”,“严格缩进”。。。

不然会报错!重要的事多说几遍!

2、一开始为什么要说Python3.6呢?因为Python3.X和Python2.X有很大的差别

附上详情http://blog.csdn.net/samxx8/article/details/21535901

Python3.X中的urlopen属性无法添加,已经很以前版本的用法根本不一样,

我也刚接触Python,找了很多方法都没有效果

比如:import urllib.request或者该文件名,都不可行

报错:

Traceback (most recent call last):
  File "E:\pythontest\gettupian.py", line 26, in <module>
    html = getHtml("http://tieba.baidu.com/p/xxxx")
  File "E:\pythontest\gettupian.py", line 9, in getHtml
    page = urllib.urlopen(url)  #urllib.urlopen()方法用于打开一个URL地址
AttributeError: module 'urllib' has no attribute 'urlopen'
3、遂重新下载了Python2.7版本,urlopen问题完美解决

4、先在D盘里新建文件夹pythonPath用来保存下载的图片

d:\\pythonPath

5、源码:

# -*- coding: UTF-8 -*-
import os,re,urllib,uuid

#首先定义云端的网页,以及本地保存的文件夹地址
urlPath='https://image.baidu.com/search/index?tn=baiduimage&ipn=r&ct=201326592&cl=2&lm=-1&st=-1&fm=result&fr=&sf=1&fmq=1488423570520_R&pv=&ic=0&nc=1&z=&se=1&showtab=0&fb=0&width=&height=&face=0&istype=2&ie=utf-8&word=%E7%81%AB%E5%BD%B1jpg'
localPath='d:\\pythonPath'


#从一个网页url中获取图片的地址,保存在
#一个list中返回
def getUrlList(urlParam):
	urlStream=urllib.urlopen(urlParam)
	htmlString=urlStream.read()
	if( len(htmlString)!=0 ):
		patternString=r'http://.{0,50}\.jpg'
		searchPattern=re.compile(patternString)
		imgUrlList=searchPattern.findall(htmlString)
		return imgUrlList

		
#生成一个文件名字符串	
def generateFileName():
	return str(uuid.uuid1())

	
#根据文件名创建文件	
def createFileWithFileName(localPathParam,fileName):
	totalPath=localPathParam+'\\'+fileName
	if not os.path.exists(totalPath):
		file=open(totalPath,'a+')
		file.close()
		return totalPath
	

#根据图片的地址,下载图片并保存在本地	
def getAndSaveImg(imgUrl):
	if( len(imgUrl)!= 0 ):
		fileName=generateFileName()+'.jpg'
		urllib.urlretrieve(imgUrl,createFileWithFileName(localPath,fileName))





#下载函数
def downloadImg(url):
	urlList=getUrlList(url)
	for urlString in urlList:
		getAndSaveImg(urlString)
		
downloadImg(urlPath)

6、运行结果:


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值