python3实现简单爬虫功能
来源:互联网 发布:mac中强制删除文件夹 编辑:程序博客网 时间:2024/05/17 08:10
本文参考虫师python2实现简单爬虫功能,并增加自己的感悟。
#coding=utf-8import reimport urllib.requestdef getHtml(url): page = urllib.request.urlopen(url) html = page.read() #print(type(html)) html = html.decode('UTF-8') #print(html) return htmldef getImg(html): reg = r'img class="BDE_Image" src="(.+?\.jpg)"' imgre = re.compile(reg) #print(type(imgre)) #print(imgre) imglist = re.findall(imgre,html) #print(type(imglist)) #print(imglist) num = 0 for imgurl in imglist: urllib.request.urlretrieve(imgurl,'D:\img\hardaway%s.jpg' %num) num+=1 html = getHtml("http://tieba.baidu.com/p/1569069059")print(getImg(html))
- re-python自带模块,用于正则表达式的相关操作
- https://docs.python.org/3/library/re.html
- urllib.request,来自扩展库urllib,用于打开网址相关操作
https://docs.python.org/3/installing/index.html
先定义了一个getHtml()函数
- 使用urllib.request.urlopen()方法打开网址
- 使用read()方法读取网址上的数据
使用decode()方法指定编码格式解码字符串
我这里指定的编码格式为UTF-8,根据页面源代码得出:
再定义了一个getImg()函数,用于筛选整个页面数据中我们所需要的图片地址
根据需要的图片来编写正则表达式 reg = r’img class=”BDE_Image” src=”(.+?.jpg)”’
上文中的例子所编写的编码格式是通过查看网页源代码的方式得知的,后来我尝试了下通过正则表达式去匹配获取charset定义的编码格式,然后指定使用匹配来的编码格式。
def getHtml(url): page = urllib.request.urlopen(url) html = page.read() #print(type(html)) rehtml = str(html) #print(type(rehtml)) reg = r'content="text/html; charset=(.+?)"' imgre = re.compile(reg) imglist = re.findall(imgre,rehtml) print(type(imglist)) code = imglist[0] print(type(code)) html = html.decode('%s' %code) return html
说一说这里的思路,html = page.read()方法处理后,返回的为bytes对象。而re.findall()方法是无法在一个字节对象上使用字符串模式的
所以我新定义了一个变量rehtml,使用str()方法把html的值转为了字符串,供re.findall()方法使用
定义了一个新变量code用来放编码格式的值,因为re.findall()方法获取回来的是列表类型,我需要使用的是字符串类型。
0 0
- python3实现简单爬虫功能
- Python3实现简单爬虫
- 用Python3实现一个简单的爬虫。
- python实现简单爬虫功能
- python实现简单爬虫功能
- python实现简单爬虫功能
- python实现简单爬虫功能
- python实现简单爬虫功能
- python实现简单爬虫功能
- python实现简单爬虫功能
- python实现简单爬虫功能
- python实现简单爬虫功能
- python实现简单爬虫功能
- python实现简单爬虫功能
- python实现简单爬虫功能
- python实现简单爬虫功能
- python实现简单爬虫功能
- python实现简单爬虫功能
- hdu 1016 Prime Ring Problem
- Maven(二)——eclipse使用Maven创建(Java和Android)项目
- IplImage,CvMat ,Mat关系与转换
- 从FineReport看开放式引擎API
- HDU 1021-Fibonacci Again
- python3实现简单爬虫功能
- 命令行运行java程序*.jar包
- [C++]高效定义STL比较函数的一些建议
- 设计模式之命令模式
- HyperPacer目标即场景
- 高并发文件下载服务器配置
- Java日历类Calendar
- DatePickerDialog和TimePickerDialog的简单使用
- Swift比Objective-C有什么优势