Python爬虫实例教程网页信息抓取功能示例【URL与正则模块】
来源:
中文源码网 浏览:266 次 日期:2024-03-28 11:43:08
【下载文档: Python爬虫实例教程网页信息抓取功能示例【URL与正则模块】.txt 】
Python爬虫实现网页信息抓取功能示例【URL与正则模块】
本文实例讲述了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查看他的标题标签是如何构造的,比如说百度贴吧是
…………
那我们就匹配reg=re.compile(r'(.*?)。')来抓取这个信息
标题抓取完我们要开始抓去正文了,我们知道正文会有很多段,所以我们要循环的去抓取整个items,这里我们注意
对于文本的读写操作,一定要放在循环外。同时加入一些去除超链接、
等机制
最后,我们在主函数调用即可
完整代码:
# -*- coding:utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf8')
#爬虫之网页信息抓取
#需要的函数方法:urllib,re,urllib2
import 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'(.*?)。')
#返回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 ">(.*?)