Python 简单网页爬虫学习
2015-10-09 14:59
585 查看
#coding=utf-8 # 参考文章: # 1. python实现简单爬虫功能 # http://www.cnblogs.com/fnng/p/3576154.html # 2. Python 2.7 时间和日期模块常用的例子 # http://www.linuxidc.com/Linux/2015-06/118458.htm # 3. Python open读写文件实现脚本 # http://www.jb51.net/article/15709.htm # 4. python re 模块 findall 函数用法简述 # http://blog.csdn.net/cashey1991/article/details/8875213 # 5. [Python]编码声明:是coding:utf-8还是coding=urf-8呢 # http://www.xuebuyuan.com/975181.html # urllib模块提供的上层接口,使我们可以像读取本地文件一样读取www和ftp上的数据。 import urllib import re import datetime,time # 定义了一个getHtml()函数 def getHtml( url ): # urllib.urlopen()方法用于打开一个URL地址。 page = urllib.urlopen( url ) # read()方法用于读取URL上的数据 html = page.read() # 返回整个网页数据 return html # 创建getImg()函数 def getImg( html ): # ()表示所要提取的字符串,即: 图片名.jpg reg = r'src="(.+?\.jpg)" pic_ext' # 可以把正则表达式编译成一个正则表达式对象. imgre = re.compile( reg ) # 读取html 中包含 imgre(正则表达式)的数据。 # 当给出的正则表达式中带有一个括号时,列表的元素为字符串, # 此字符串的内容与括号中的正则表达式相对应(不是整个正则表达式的匹配内容)。 imglist = re.findall( imgre, html ) print "Start downloading the first five pictures" # 通过一个for循环对获取的图片连接进行遍历,为了使图片的文件名看上去更规范, # 对其进行重命名,命名规则通过x变量加1。保存的位置默认为程序的存放目录。 x = 0 for imgurl in imglist: # 用到了urllib.urlretrieve()方法,直接将远程数据下载到本地 urllib.urlretrieve( imgurl, '%s.jpg' % x ) # python不支持类似 x++ 或 x-- 这样的前置/后置自增/自减运算符,因此只能用 += 或 -= 这种。 x += 1 # 这里面的图片可能比较多,我们测试前五张就差不多了 if x == 5 : break print "the first five pictures download completed." return imglist # 向getHtml()函数传递一个网址,并把整个页面下载下来,保存在html变量中 html = getHtml( "http://www.zengjf.org" ) # 合成要保存的文件名,由年月日、时分秒组成,以只写方式打开文件 saveFile = open( time.strftime( "%Y%m%d%H%M%S" ) + ".html", 'w' ) saveFile.write( html ) # 将html中的内容写入文件 saveFile.close( ) # 关闭文件 html = getHtml( "http://tieba.baidu.com/p/2460150866" ) print getImg( html )
相关文章推荐
- python学习网站
- Python中的时间和日期
- 用python解析html--SGMLParser
- python 字符串GBK解码
- python异常处理
- Python相对完美的URL拼接函数
- Windows通过Python登录服务器----Telnet
- 2.Python标准库_ 时间与日期 (time, datetime包)
- Python 面向对象
- Python(一)初学小实验
- mac os安装 brew 及 cffi
- Python——UnicodeEncodeError: 'ascii' codec can't encode/decode characters
- Python判断IP合法性
- Python模拟鼠标点击
- Google Protocol Buffer安装及在python中的使用
- python---把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字
- python3爬虫之入门基础和正则表达式
- Python基础总结
- 机器学习编程语言之争,Python 夺魁【转载+整理】
- python 模块概念