python小实例一:简单爬虫
2017-03-27 11:52
507 查看
本文所谓的爬虫就是通过本地远程访问url,然后将url的读成源代码形式,然后对源代码进行解析,获取自己需要的数据,相当于简单数据挖掘。本文实现的是将一个网页的图片爬出保存到本地的过程,例子很简单,用的是python 3.5.2版本,以前的版本可能导入的包的名字不一样,调用的库函数方式有些差别。代码如下:
#coding =utf-8 import urllib.request import re def getHtml(url): page = urllib.request.urlopen(url) ##打开页面 html = page.read() ##获取目标页面的源码 return html def getImg(html): reg = 'src="(.+?\.png)"' ##正则表达式筛选目标图片格式,有些是'data-original="(.+?\.jpg)"' img = re.compile(reg) html = html.decode('utf-8') ##编码方式为utf-8 imglist = re.findall(img, html) ##解析页面源码获取图片列表 #print(imglist) x = 0 #length = len(imglist) for i in range(6): ##取前6张图片保存 imgurl = imglist[i] #imgurl = re.sub('"(.*?)"',r'\1',imgurl) #取单引号里的双引号内容 #print(imgurl) urllib.request.urlretrieve(imgurl,'%s.jpg' % x) ##将图片从远程下载到本地并保存 x += 1 global Max_Num Max_Num = 1 ##有时候无法打开目标网页,需要尝试多次,这里设置为1次 for i in range(Max_Num): try: html = getHtml("view-source:http://www.shangxueba.com/jingyan/2438398.html") getImg(html) break except: if i < Max_Num - 1: continue else: print ('URLError: <urlopen error timed out> All times is failed ')
相关文章推荐
- Python入门(一):爬虫基本结构&简单实例
- python爬虫系列(1)——一个简单的爬虫实例
- Python简单爬虫导出CSV文件的实例讲解
- 简单Python爬虫实例
- python_慕课\Python开发简单爬虫\5-3 Python爬虫urlib2实例代码.py
- python用BeautifulSoup库简单爬虫实例分析
- 从一个简单的爬虫实例看python2和python3的区别
- Python爬虫的简单入门及实用的实例(1)
- Python爬虫的post请求简单实例
- Python---BeautifulSoup 简单的爬虫实例
- python一个简单的爬虫实例
- python妹子图简单爬虫实例
- Python 爬虫 简单实例 爬取糗事百科段子
- $python爬虫系列(1)——一个简单的爬虫实例
- Python简单爬虫实例记录
- Python 网络爬虫--关于简单的模拟登录实例讲解
- Python爬虫实例(5)-简单的爬虫,用XML爬取卡车图片
- python3爬虫超简单实例
- Python---BeautifulSoup 简单的爬虫实例
- Python简单爬虫实例