Python爬虫实现网页信息抓取功能示例【URL与正则模块】
作者:九日王朝 时间:2023-12-09 05:15:03
本文实例讲述了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')
PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:
JavaScript正则表达式在线测试工具:
http://tools.jb51.net/regex/javascript
正则表达式在线生成工具:
http://tools.jb51.net/regex/create_reg
希望本文所述对大家Python程序设计有所帮助。
标签:Python,爬虫,抓取,正则
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
asp中的rs.open与conn.execute的区别说明
2011-02-24 10:56:00
bootstrap table单元格新增行并编辑
2024-04-10 16:09:09
![](https://img.aspxhome.com/file/2023/9/136789_0s.jpg)
Python数据结构详细
2022-10-03 21:02:00
Python3+OpenCV2实现图像的几何变换(平移、镜像、缩放、旋转、仿射)
2022-01-24 03:20:13
![](https://img.aspxhome.com/file/2023/3/93793_0s.jpg)
不同操作系统下的mysql数据库同步
2008-12-22 14:41:00
如何使用AspUpload2.0组件?
2010-06-05 12:33:00
Mysql数据库性能优化三(分表、增量备份、还原)
2024-01-21 00:38:54
![](https://img.aspxhome.com/file/2023/9/92769_0s.png)
python flask中静态文件的管理方法
2022-12-11 01:32:40
SQL Server 存储过程遇到“表 ''#TT'' 没有标识属性无法执行 SET 操作”错误
2024-01-24 00:07:57
![](https://img.aspxhome.com/file/2023/8/85598_0s.png)
Python实现求两个数组交集的方法示例
2023-08-03 18:57:58
javascript preload&lazy load
2023-09-01 06:15:43
在keras中对单一输入图像进行预测并返回预测结果操作
2023-03-10 10:07:04
![](https://img.aspxhome.com/file/2023/2/118802_0s.jpg)
bootstrapValidator bootstrap-select验证不可用的解决办法
2024-04-10 13:53:06
Sql注入工具_动力节点Java学院整理
2024-01-20 00:02:10
![](https://img.aspxhome.com/file/2023/5/122415_0s.jpg)
Python中模拟enum枚举类型的5种方法分享
2022-05-04 01:00:10
MySQL删除外键、增加外键以及删除主键、增加主键的实战步骤
2024-01-26 00:58:52
![](https://img.aspxhome.com/file/2023/7/121287_0s.jpg)
慢慢的网页
2009-11-12 12:53:00
![](https://img.aspxhome.com/file/UploadPic/200911/12/manmanwangye-95s.jpg)
Python多线程实例教程
2022-11-30 14:15:43
在 Python 中使用 7zip 备份文件的操作
2022-10-01 10:05:56
c#实现数据库事务示例分享
2024-01-28 05:03:02