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,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'<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')
    





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值