初学Python----urllib2模块与正则表达式组合而成的小爬虫
2014-07-12 15:30
806 查看
最近开始学Python,在http://www.the5fire.com/python-sohuspider-software-people.html这个博客上看到作者写的简单的从搜狐上爬小说的爬虫,正好学习学习练练手,发现代码是几年前的,而搜狐网早已经更新了网页,原代码已经不能用了,正好我来改改。下面是改过之后的代码,亲测有效:
爬下来的小说格式非常粗糙,有待改进!
感谢原作者!
#!/usr/bin/python import re import urllib2 import sys def getPage(url,offset = '3399'): realurl = "%s%s%s" % (url,offset,".html") print realurl content = urllib2.urlopen(realurl).read() content_re = re.compile(r'<div class="chapter"></div>\n(.*[\n])+?[\t]</div>') try: content_list = content_re.search(content,re.S).group(0) except Exception,e: print str(e) return contentresult = content_list fp = open(r'renxingruanjian.txt','a') contentresult = contentresult.replace('<div class="chapter"></div>','') contentresult = contentresult.replace('</p><p>','') contentresult = contentresult.replace('</p></p>','') contentresult = contentresult.replace('<p><p>','') contentresult = contentresult.replace(' ','') contentresult = contentresult.replace(' ','') contentresult = contentresult.replace('</div>','') #content = content.replace(' ','') #content = content.replace(' ','') fp.write(contentresult + '\n') fp.flush() fp.close() def getBook(url,startoffset,endoffset): while startoffset < endoffset: getPage(url,offset = str(startoffset)) startoffset += 1 if __name__ == '__main__': getBook(url = 'http://lz.book.sohu.com/chapter-121',startoffset = 3399,endoffset = 3426)
爬下来的小说格式非常粗糙,有待改进!
感谢原作者!
相关文章推荐
- python爬虫入门(1) 基础知识 ; 正则表达式 Re 模块
- python爬虫常用正则表达式组合匹配
- python3爬虫(二) re模块与正则表达式
- python 爬虫004-使用urllib2与正则表达式扒取糗事百科新鲜页首页帖子
- 04 Python正则表达式 爬虫程序 变量的引用,浅拷贝,深拷贝 多线程 进程锁 数据库模块
- Python爬虫实践(八):正则表达式re模块(2)
- python爬虫主要就是五个模块:爬虫启动入口模块,URL管理器存放已经爬虫的URL和待爬虫URL列表,html下载器,html解析器,html输出器 同时可以掌握到urllib2的使用、bs4(BeautifulSoup)页面解析器、re正则表达式、urlparse、python基础知识回顾(set集合操作)等相关内容。
- Python爬虫实践(七):正则表达式(2) re模块的使用
- python爬虫入门(2)re模块-正则表达式
- Python爬虫实例(4)-用urllib、re和正则表达式爬取网页图片
- Python3.7 爬虫(一)使用 Urllib2 与正则表达式抓取
- Python笔记(8)re模块,正则表达式
- Python 之 【re模块的正则表达式学习】
- Python中re(正则表达式)模块学习
- Python中re(正则表达式)模块学习
- Python用re(正则表达式)模块过滤Telnet字体颜色
- Python中re(正则表达式)模块学习
- Python 正则表达式 RE模块的使用方法
- Python中re(正则表达式)模块函数学习
- python的正则表达式re模块的常用方法