python抓取网页数据(本文实例讲述Python爬虫实现网页信息抓取功能(图))

优采云 发布时间: 2021-12-10 03:09

  python抓取网页数据(本文实例讲述Python爬虫实现网页信息抓取功能(图))

  本文介绍了Python爬虫实现爬取网页信息的功能。分享给大家,供大家参考,如下:

  首先,我们需要使用以下模块来实现网页的解析、阅读等操作

  

import urllib

import urllib2

import re

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

  

def test():

f=urllib.urlopen('http://www.baidu.com')

while True:

firstLine=f.readline()

print firstLine

  说一下如何实现网页信息抓取,比如*敏*感*词*

  我们大概需要做几件事:

  首先获取网页及其代码。这里需要实现多个页面,即它的URL会发生变化,我们传递一个页码

  

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=pile(r'(.*?).') 来抓取这个信息

  抓取标题后,我们将开始抓取正文。我们知道body中会有很多段落,所以我们需要循环爬取整个item。这里我们注意

  对于文本读写操作,必须放在循环之外。同时添加一些去除超链接,

  机制

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

  完整代码:

  

# -*- 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 ">(.*?)')

#返回list列表

items=re.findall(reg,html)

f=open('output.txt','a+')

#[1:]切片,第一个元素不需要,去掉。

for i in items[1:]:

#超链接去除

removeAddr=re.compile(&#39;|</a>&#39;)

#用""替换

i=re.sub(removeAddr,"",i)

#

去除

i=i.replace(&#39;

&#39;,&#39;&#39;)

f.write(&#39;\n\n&#39;+i.encode(&#39;gbk&#39;))

f.close()

#调用入口

baseURL=&#39;http://tieba.baidu.com/p/4638659116&#39;

bdtb=BDTB(baseURL,1)

print &#39;爬虫正在启动....&#39;.encode(&#39;gbk&#39;)

#多页

bdtb.Title()

print &#39;抓取标题完毕!&#39;.encode(&#39;gbk&#39;)

for i in range(1,11):

print &#39;正在抓取第d页&#39;.encode(&#39;gbk&#39;)%i

bdtb.Text(i)

print &#39;抓取正文完毕!&#39;.encode(&#39;gbk&#39;)

  希望这篇文章对你的Python编程有所帮助。

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线