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

http://www.jianshu.com/p/8778b144eb3f

# -*- coding:utf-8 -*-
import urllib
import urllib2

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

user_agent='Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36'
headers={'User-Agent':user_agent}

request=urllib2.Request(url,headers=headers)
response=urllib2.urlopen(request)
str_html= response.read()
response.close()

print str_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. 获取每个楼层的内容

# -*- coding:utf-8 -*-
from lxml import html  
import urllib
import urllib2

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

user_agent='Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36'
headers={'User-Agent':user_agent}

request=urllib2.Request(url,headers=headers)
response=urllib2.urlopen(request)
str_html= response.read()
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解析完以后输出就中文乱码了。

 
 

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

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

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

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

# -*- coding:utf-8 -*-
from lxml import html
import urllib
import urllib2

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

user_agent='Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36'
headers={'User-Agent':user_agent}

request=urllib2.Request(url,headers=headers)
response=urllib2.urlopen(request)
str_html= response.read()
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正则表达式指南



完整代码:
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):
        self.url_base=self.url_base+see_lz
    
    def setPage(self,page):
        self.url=self.url_base+'&pn='+page
    
    def printPage(self):
        request=urllib2.Request(self.url)
        response=urllib2.urlopen(request)
        str_html=response.read()
        response.close()
        
        str_html=unicode(str_html,'utf-8')
        
        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):
    crawl_bdtb.setPage(str(i+1))
    crawl_bdtb.printPage()


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值