您的位置:首页 > 编程语言 > Python开发

Python爬虫实现网页信息抓取功能示例【URL与正则模块】

2017-05-18 11:34 1321 查看

本文实例讲述了Python爬虫实现网页信息抓取功能。分享给大家供大家参考,具体如下:

首先实现关于网页解析、读取等操作我们要用到以下几个模块

import urllib
import urllib2
import re

我们可以尝试一下用readline方法读某个网站,比如说百度

def test():
f=urllib.urlopen('http://www.baidu.com')
while True:
firstLine=f.readline()
print firstLine

下面我们说一下如何实现网页信息的抓取,比如说百度贴吧

我们大概要做几件事情:

首先获取网页及其代码,这里我们要实现多页,即其网址会改变,我们传递一个页数

def getPage(self,pageNum):
try:
url=self.baseURL+self.seeLZ+'&pn='+str(pageNum)
#创建request对象
request=urllib2.Request(url)
response=urllib2.urlopen(request)
#print 'URL:'+url
return response.read()
except Exception,e:
print e

之后我们要获取小说内容,这里咱们分为标题和正文。标题每页都有,所以我们获取一次就好了。

我们可以点击某网站,按f12查看他的标题标签是如何构造的,比如说百度贴吧是<title>…………

那我们就匹配

reg=re.compile(r'<title>(.*?)。')
来抓取这个信息

标题抓取完我们要开始抓去正文了,我们知道正文会有很多段,所以我们要循环的去抓取整个items,这里我们注意

对于文本的读写操作,一定要放在循环外。同时加入一些去除超链接、<br>等机制

最后,我们在主函数调用即可

完整代码:

# -*- coding:utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
#爬虫之网页信息抓取
#需要的函数方法:urllib,re,urllib2import urllib
import urllib2
import re#测试函数->读取
#def test():
#   f=urllib.urlopen('http://www.baidu.com')
#   while True:
#     firstLine=f.readline()
#     print firstLine
#针对于百度贴吧获取前十页楼主小说文本内容
class BDTB:
def __init__(self,baseUrl,seeLZ):
#成员变量
self.baseURL=baseUrl
self.seeLZ='?see_lz='+str(seeLZ)
#获取该页帖子的代码def getPage(self,pageNum):
try:
url=self.baseURL+self.seeLZ+'&pn='+str(pageNum)
#创建request对象
request=urllib2.Request(url)
response=urllib2.urlopen(request)
#print 'URL:'+url
return response.read()
except Exception,e:
print e#匹配标题
def Title(self):
html=self.getPage(1)
#compile提高正则匹配效率
reg=re.compile(r'<title>(.*?)。')
#返回list列表
items=re.findall(reg,html)
f=open('output.txt','w+')
item=('').join(items)
f.write('\t\t\t\t\t'+item.encode('gbk'))
f.close()
#匹配正文
def Text(self,pageNum):
html=self.getPage(pageNum)
#compile提高正则匹配效率
reg=re.compile(r'"d_post_content j_d_post_content ">(.*?)</div>')
#返回list列表
items=re.findall(reg,html)
f=open('output.txt','a+')
#[1:]切片,第一个元素不需要,去掉。
for i in items[1:]:
#超链接去除
removeAddr=re.compile('<a.*?>|</a>')
#用""替换
i=re.sub(removeAddr,"",i)
#<br>去除
i=i.replace('<br>','')
f.write('\n\n'+i.encode('gbk'))
f.close()
#调用入口
baseURL='http://tieba.baidu.com/p/4638659116'
bdtb=BDTB(baseURL,1)
print '爬虫正在启动....'.encode('gbk')
#多页
bdtb.Title()
print '抓取标题完毕!'.encode('gbk')
for i in range(1,11):
print '正在抓取第%02d页'.encode('gbk')%i
bdtb.Text(i)
print '抓取正文完毕!'.encode('gbk')

PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:

JavaScript正则表达式在线测试工具:
http://tools.jb51.net/regex/javascript

正则表达式在线生成工具:
http://tools.jb51.net/regex/create_reg

更多关于Python相关内容可查看本站专题:《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python 爬虫 抓取 正则