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


Posted in Python onMay 18, 2017

本文实例讲述了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')
Python 相关文章推荐
Python BeautifulSoup中文乱码问题的2种解决方法
Apr 22 Python
详解Python之数据序列化(json、pickle、shelve)
Mar 30 Python
python爬虫实战之爬取京东商城实例教程
Apr 24 Python
Python编程之string相关操作实例详解
Jul 22 Python
Python爬虫实例扒取2345天气预报
Mar 04 Python
python实现求解列表中元素的排列和组合问题
Mar 15 Python
mac下如何将python2.7改为python3
Jul 13 Python
python得到电脑的开机时间方法
Oct 15 Python
Python 自动登录淘宝并保存登录信息的方法
Sep 04 Python
Python搭建代理IP池实现获取IP的方法
Oct 27 Python
Pycharm及python安装详细步骤及PyCharm配置整理(推荐)
Jul 31 Python
增大python字体的方法步骤
Jul 05 Python
Python使用time模块实现指定时间触发器示例
May 18 #Python
Python实现的文本简单可逆加密算法示例
May 18 #Python
Python操作MongoDB详解及实例
May 18 #Python
Python 迭代器与生成器实例详解
May 18 #Python
Python字符串处理实例详解
May 18 #Python
Python进阶-函数默认参数(详解)
May 18 #Python
Python装饰器实现几类验证功能做法实例
May 18 #Python
You might like
php2html php生成静态页函数
2008/12/08 PHP
PHP手机短信验证码实现流程详解
2018/05/17 PHP
Laravel框架实现多数据库连接操作详解
2019/07/12 PHP
动态加载iframe
2006/06/16 Javascript
在模板页面的js使用办法
2010/04/01 Javascript
中文输入法不触发onkeyup事件的解决办法
2014/07/09 Javascript
JS+DIV+CSS实现的经典标签切换效果代码
2015/09/14 Javascript
基于zepto的移动端轻量级日期插件--date_picker
2016/03/04 Javascript
修改js confirm alert 提示框文字的简单实例
2016/06/10 Javascript
jQuery列表检索功能实现代码
2017/07/17 jQuery
浅谈Angular文字折叠展开组件的原理分析
2017/11/24 Javascript
js 公式编辑器 - 自定义匹配规则 - 带提示下拉框 - 动态获取光标像素坐标
2018/01/04 Javascript
ES6 对象的新功能与解构赋值介绍
2019/02/05 Javascript
通过实例讲解JS如何防抖动
2019/06/15 Javascript
JavaScript随机数的组合问题案例分析
2020/05/16 Javascript
[25:45]2018DOTA2亚洲邀请赛4.5SOLO赛 Sylar vs Paparazi
2018/04/06 DOTA
如何在python中使用selenium的示例
2017/12/26 Python
Python编程求解二叉树中和为某一值的路径代码示例
2018/01/04 Python
Python 数据可视化pyecharts的使用详解
2019/06/26 Python
python获取指定日期范围内的每一天,每个月,每季度的方法
2019/08/08 Python
python字典的遍历3种方法详解
2019/08/10 Python
Python的Lambda函数用法详解
2019/09/03 Python
Python数据库小程序源代码
2019/09/15 Python
Python爬虫爬取Bilibili弹幕过程解析
2019/10/10 Python
python传到前端的数据,双引号被转义的问题
2020/04/03 Python
Python pytesseract验证码识别库用法解析
2020/06/29 Python
有关pycharm登录github时有的时候会报错connection reset的问题
2020/09/15 Python
Skyscanner澳大利亚:全球领先的旅游搜索网站
2018/03/24 全球购物
《灯光》教学反思
2014/02/08 职场文书
秋天的图画教学反思
2014/05/01 职场文书
热门专业求职信
2014/05/24 职场文书
庆元旦演讲稿
2014/09/15 职场文书
学习十八大宣传标语
2014/10/09 职场文书
门市房租房协议书
2014/12/04 职场文书
Python+Tkinter打造签名设计工具
2022/04/01 Python
安装Windows Server 2012 R2企业版操作系统并设置好相关参数
2022/04/29 Servers