python爬虫怎么爬贴吧_python爬虫入门 实战(二)---爬百度贴吧

本篇涉及知识点:

1、xpath语法

2、正则表达式

踩坑:

1、xpath解析出的结点文本内容中文乱码。

2、xpath解析时,结点内有多余标签,文本被截断。

3、用正则表达式匹配的分组输出乱码。

发送请求获取html文本内容

import urllib2

#目标url,这里see_lz=1代表只看楼主,pn=1代表页码为1

url='https://tieba.baidu.com/p/3267113128?see_lz=1&pn=1’

request=urllib2.Request(url)#封装请求

response=urllib2.urlopen(request)#打开url资源,得到响应

str_html=response.read()#读取html文本内容

response.close()#关闭资源

print str_html#打印html文本

我们看输出结果,这里中文是正常,没有乱码的:

html文本输出

xpath解析并获取每一个楼层的内容

1. 我们先来分析html文本结构

点击左边小红框的按钮再点击目标,即可查看到相应的标签。

楼层内容的标签

可以看到这个div有很明显的特征,id=“post_content_56723422722”,即id包括字段“post_content_”,我们可以直接用contains函数通过id来找到。

tree.xpath('//div[contains(@id,"post_content_")]']

不过为了保险起见,也为了多熟悉一下xpath解析的语法,我们多往上看两层。目标是class=“d_post_content_main ”的div下的一个class=“p_content ”的div里的cc标签下的唯一div。

所以我们可以用以下语句找到所有楼层的目标内容:

tree.xpath('//div[@class="d_post_content_main "]/div[@class="p_content "]/cc/div')

同理我们可以分析结构,解析得到相应的楼层号:

tree.xpath('//div[@class="d_post_content_main "]/div[@class="core_reply j_lzl_wrapper"]/div[@class="core_reply_tail clearfix"]/div[@class="post-tail-wrap"]/span[2]')

2. 获取每个楼层的内容

import urllib2

from lxml import html

url='https://tieba.baidu.com/p/3267113128?see_lz=1&pn=1'#目标url

request=urllib2.Request(url)#封装请求

response=urllib2.urlopen(request)#打开url资源,得到响应

str_html=response.read()#读取html文本内容

response.close()#关闭资源

tree=html.fromstring(str_html)

nodes=tree.xpath('//div[@class="d_post_content_main "]')#先找的所有的楼层再进一步解析楼层号码和内容

for node in nodes:

layer=node.xpath('div[@class="core_reply j_lzl_wrapper"]/div[@class="core_reply_tail clearfix"]/div[@class="post-tail-wrap"]/span[2]')[0].text

print layer#输出楼层号

content=node.xpath('div[@class="p_content "]/cc/div')[0].text

print content#输出楼层内容

这里就出现第一个坑了,前面输出html文本是没有中文乱码的,这里xpath解析完以后输出就中文乱码了。运行一下看输出结果:

xpath解析中文乱码

不过在python里内置了unicode字符类型,这是解决乱码问题的神器。将str类型的字符串转换成unicode字符类型就可以了。转换方法有两种:

s1 = u"字符串"

s2 = unicode("字符串", "utf-8")

想具体了解unicode和python里的乱码问题的,可以参考这一篇博客:关于Python的编码、乱码以及Unicode的一些研究

下面看修改后的代码:

注:因为一楼的div的class有两个,所以将获取每个楼层结点的代码改成有contains函数

import urllib2

from lxml import html

url='https://tieba.baidu.com/p/3267113128?see_lz=1&pn=1'#目标url

request=urllib2.Request(url)#封装请求

response=urllib2.urlopen(request)#打开url资源,得到响应

str_html=response.read()#读取html文本内容

response.close()#关闭资源

str_html=unicode(str_html,'utf-8')#将string字符类型转换成unicode字符类型

tree=html.fromstring(str_html)

nodes=tree.xpath('//div[contains(@class,"d_post_content_main")]')#先找的所有的楼层再进一步解析楼层号码和内容

for node in nodes:

layer=node.xpath('div[@class="core_reply j_lzl_wrapper"]/div[@class="core_reply_tail clearfix"]/div[@class="post-tail-wrap"]/span[2]')[0].text

print layer#输出楼层号

content=node.xpath('div[@class="p_content "]/cc/div')[0].text

print content#输出楼层内容

运行可以看到结果里有一些楼层的输出内容不完整,这就是第二个坑:

楼层不完整

我们返回浏览器查看结构,可以发现,原来是这个div里有其他标签(a和br),不是纯文本的。这里就可以用string函数来过滤掉多余的标签。

在前面的代码里,输出楼层的语句换成:

content=node.xpath('div[@class="p_content "]/cc/div')[0]

content_txt=content.xpath('string(.)')#用string函数过滤掉多余子标签,.代表本结点

print content_txt#输出楼层内容

但是br也被过滤掉了,有些楼层有分序号的输出结果也是一行,看着不方便。我们可以用正则表达式匹配上数字序号,并在之前插入换行符“\n”。re模块的sub是匹配并替换字符串的方法。python中正则表达式的更多使用可以参考Python正则表达式指南。

re_num=re.compile('([0-9]\.)') #匹配所有的数字序号(数字后通常跟"."),加上括号作为分组1,这样可以进行替换的时候用上

for node in nodes:

layer=node.xpath('div[@class="core_reply j_lzl_wrapper"]/div[@class="core_reply_tail clearfix"]/div[@class="post-tail-wrap"]/span[2]')[0].text

print layer#输出楼层号

content=node.xpath('div[@class="p_content "]/cc/div')[0]

content_txt=content.xpath('string(.)')

content_txt=re.sub(re_num,'\n\1',content_txt) #将目标匹配替换成换行符+本身分组(也就是分组1)

print content_txt #输出楼层内容

但输出结果显示,换行成功了,数字序号成了乱码。这里是第三个坑,漏掉了一个小地方。

修改倒数第二句为:

content_txt=re.sub(re_num,r'\n\1',content_txt)#加上一个字母'r'

这个“r”是代表防止字符转义,也就是“original”原生字符。关于正则中字符的转义,有兴趣的同学可以google、百度。

接下来我们简单将代码写成面向对象的风格。完整代码如下:

import urllib2

from lxml import html

import re

class BaiduTieba:

url_base='https://tieba.baidu.com/p/3267113128?see_lz='

file = open("../text/bdtb.txt","w+")

def __init__(self,see_lz):#see_lz=1表示只看楼主

self.url_base=self.url_base+see_lz

def setPage(self,page):

self.url=self.url_base+'&pn='+page#目标url

def printPage(self):

request=urllib2.Request(self.url)#封装请求

response=urllib2.urlopen(request)#打开url资源,得到响应

str_html=response.read()#读取html文本内容

response.close()#关闭资源

str_html=unicode(str_html,'utf-8')#将string字符类型转换成unicode字符类型

tree=html.fromstring(str_html)

nodes=tree.xpath('//div[contains(@class,"d_post_content_main")]')#先找的所有的楼层再进一步解析楼层号码和内容

re_num=re.compile('([0-9]\.)')

for node in nodes:

layer=node.xpath('div[@class="core_reply j_lzl_wrapper"]/div[@class="core_reply_tail clearfix"]/div[@class="post-tail-wrap"]/span[2]')[0].text

self.file.write("\n")

self.file.write("vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv\n")

self.file.write("------------------------------------------------------------------------------------\n")

self.file.write(" "+layer.encode("utf-8")+" \n")

self.file.write("------------------------------------------------------------------------------------\n")

content=node.xpath('div[@class="p_content "]/cc/div')[0]

content_txt=content.xpath('string(.)')

content_txt=re.sub(re_num,r'\n\1',content_txt)

self.file.write(content_txt.encode("utf-8"))#输出楼层内容

self.file.write("------------------------------------------------------------------------------------\n")

crawl_bdtb=BaiduTieba("1")

for i in range(5):#爬5页

crawl_bdtb.setPage(str(i+1))

crawl_bdtb.printPage()

爬取结果截图:

爬取结果

参考

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值