【Python】Python简易爬虫爬取百度贴吧图片
2017-07-31 17:51
483 查看
通过python 来实现这样一个简单的爬虫功能,把我们想要的图片爬取到本地。(Python版本为3.6.0)
一.获取整个页面数据
def getHtml(url): page=urllib.request.urlopen(url) html=page.read() return html
说明:
向getHtml()函数传递一个网址,就可以把整个页面下载下来.
urllib.request 模块提供了读取web页面数据的接口,我们可以像读取本地文件一样读取www和ftp上的数据.
二.筛选页面中想要的数据
在百度贴吧找到了几张漂亮的图片,想要下载下来.使用火狐浏览器,在图片位置鼠标右键单单击有查看元素选项,点进去之后就会进入开发者模式,并且定位到图片所在的前段代码
现在主要观察图片的正则特征,编写正则表达式.
reg=r'src="(https://imgsa[^>]+\.(?:jpeg|jpg))"'
#参考正则
编写代码
def getImg(html): reg=r'src="(https://imgsa[^>]+\.(?:jpeg|jpg))"' imgre = re.compile(reg) imglist = re.findall(imgre,html.decode('utf-8')) return imglist
说明:
re.compile() 可以把正则表达式编译成一个正则表达式对象.
re.findall() 方法读取html 中包含 imgre(正则表达式)的数据。
运行脚本将得到整个页面中包含图片的URL地址。
三.将页面筛选的数据保存到本地
编写一个保存的函数
def saveFile(x): if not os.path.isdir(path): os.makedirs(path) t = os.path.join(path,'%s.img'%x) return t
完整代码:
''' Created on 2017年7月15日 @author: Administrator ''' import urllib.request,os import re def getHtml(url): page=urllib.request.urlopen(url) html=page.read() return html path='D:/workspace/Python1/reptile/__pycache__/img' def saveFile(x): if not os.path.isdir(path): os.makedirs(path) t = os.path.join(path,'%s.img'%x) return t html=getHtml('https://tieba.baidu.com/p/5248432620') print(html) print('\n') def getImg(htnl): reg=r'src="(https://imgsa[^>]+\.(?:jpeg|jpg))"' imgre=re.compile(reg) imglist=re.findall(imgre,html.decode('utf-8')) x=0 for imgurl in imglist: urllib.request.urlretrieve(imgurl,saveFile(x)) print(imgurl) x+=1 if x==23: break print(x) return imglist getImg(html) print('end')
核心是用到了urllib.request.urlretrieve()方法,直接将远程数据下载到本地
相关文章推荐
- 使用简易Python爬虫下载百度贴吧图片
- python爬虫小项目:爬取百度贴吧图片
- python爬虫:下载百度贴吧图片学习笔记
- python简易爬虫编写--图片获取
- python scrapy爬虫爬取图片简易方法,使用Images模块
- 我的第一个python爬虫程序(从百度贴吧自动下载图片)
- 【简易Python爬虫】 初试爬虫_简易Python图片爬虫实现
- Python爬虫--抓取百度贴吧图片
- Python爬虫学习记录(1)——百度贴吧图片下载
- Python-简单的爬虫案例(百度贴吧-图片)
- Python爬虫实战(五) :下载百度贴吧帖子里的所有图片
- python 百度贴吧爬虫(下载图片)
- Python爬虫实战(1)——百度贴吧抓取帖子并保存内容和图片
- Python 爬虫获取百度贴吧图片
- 【Python3.6爬虫学习记录】(四)爬取百度贴吧某帖子内容及图片
- python学习:urllib库学习:制作简易爬虫下载图片
- [置顶] 【python 爬虫】百度贴吧帖子所有楼层图片爬虫
- python3 多页爬虫爬取百度贴吧帖子所有图片
- Python实现爬取百度贴吧帖子所有楼层图片的爬虫示例
- python 爬虫(一)爬取百度贴吧图片