网络爬虫(四):一个简单的百度贴吧的小爬虫

  1. # -*- coding: utf-8 -*-  
  2. #---------------------------------------  
  3. #   程序:百度贴吧爬虫  
  4. #   版本:0.1  
  5. #   作者:why  
  6. #   日期:2013-05-14  
  7. #   语言:Python 2.7  
  8. #   操作:输入带分页的地址,去掉最后面的数字,设置一下起始页数和终点页数。  
  9. #   功能:下载对应页码内的所有页面并存储为html文件。  
  10. #---------------------------------------  
  11.    
  12. import string, urllib2  
  13.    
  14. #定义百度函数  
  15. def baidu_tieba(url,begin_page,end_page):     
  16.     for i in range(begin_page, end_page+1):  
  17.         sName = string.zfill(i,5) + '.html'#自动填充成六位的文件名  
  18.         print '正在下载第' + str(i) + '个网页,并将其存储为' + sName + '......'  
  19.         f = open(sName,'w+')  
  20.         m = urllib2.urlopen(url + str(i)).read()  
  21.         f.write(m)  
  22.         f.close()  
  23.    
  24.    
  25. #-------- 在这里输入参数 ------------------  
  26.   
  27. # 这个是山东大学的百度贴吧中某一个帖子的地址  
  28. #bdurl = 'http://tieba.baidu.com/p/2296017831?pn='  
  29. #iPostBegin = 1  
  30. #iPostEnd = 10  
  31.   
  32. bdurl = str(raw_input(u'请输入贴吧的地址,去掉pn=后面的数字:\n'))  
  33. begin_page = int(raw_input(u'请输入开始的页数:\n'))  
  34. end_page = int(raw_input(u'请输入终点的页数:\n'))  
  35. #-------- 在这里输入参数 ------------------  
  36.    
  37.   
  38. #调用  
  39. baidu_tieba(bdurl,begin_page,end_page)  

[Python]网络爬虫(七):Python中的正则表达式教程

分类: 爬虫 Python   1212人阅读  评论(0)  收藏  举报

目录(?)[+]

接下来准备用糗百做一个爬虫的小例子。

但是在这之前,先详细的整理一下Python中的正则表达式的相关内容。

正则表达式在Python爬虫中的作用就像是老师点名时用的花名册一样,是必不可少的神兵利器。



一、 正则表达式基础

1.1.概念介绍

正则表达式是用于处理字符串的强大工具,它并不是Python的一部分。

其他编程语言中也有正则表达式的概念,区别只在于不同的编程语言实现支持的语法数量不同。

它拥有自己独特的语法以及一个独立的处理引擎,在提供了正则表达式的语言里,正则表达式的语法都是一样的。

下图展示了使用正则表达式进行匹配的流程:

正则表达式的大致匹配过程是:

1.依次拿出表达式和文本中的字符比较,

2.如果每一个字符都能匹配,则匹配成功;一旦有匹配不成功的字符则匹配失败。

3.如果表达式中有量词或边界,这个过程会稍微有一些不同。

下图列出了Python支持的正则表达式元字符和语法:   



1.2. 数量词的贪婪模式与非贪婪模式

正则表达式通常用于在文本中查找匹配的字符串。

贪婪模式,总是尝试匹配尽可能多的字符;

非贪婪模式则相反,总是尝试匹配尽可能少的字符。

Python里数量词默认是贪婪的。

例如:正则表达式"ab*"如果用于查找"abbbc",将找到"abbb"。

而如果使用非贪婪的数量词"ab*?",将找到"a"。


1.3. 反斜杠的问题

与大多数编程语言相同,正则表达式里使用"\"作为转义字符,这就可能造成反斜杠困扰。

假如你需要匹配文本中的字符"\",那么使用编程语言表示的正则表达式里将需要4个反斜杠"\\\\":

第一个和第三个用于在编程语言里将第二个和第四个转义成反斜杠,

转换成两个反斜杠\\后再在正则表达式里转义成一个反斜杠用来匹配反斜杠\。

这样显然是非常麻烦的。

Python里的原生字符串很好地解决了这个问题,这个例子中的正则表达式可以使用r"\\"表示。

同样,匹配一个数字的"\\d"可以写成r"\d"。

有了原生字符串,妈妈再也不用担心我的反斜杠问题~



二、 介绍re模块

2.1.  Compile

Python通过re模块提供对正则表达式的支持。

使用re的一般步骤是:

Step1:先将正则表达式的字符串形式编译为Pattern实例。

Step2:然后使用Pattern实例处理文本并获得匹配结果(一个Match实例)。

Step3:最后使用Match实例获得信息,进行其他的操作。

我们新建一个re01.py来试验一下re的应用:

[python]  view plain copy
  1. # -*- coding: utf-8 -*-  
  2. #一个简单的re实例,匹配字符串中的hello字符串  
  3.   
  4. #导入re模块  
  5. import re  
  6.    
  7. # 将正则表达式编译成Pattern对象,注意hello前面的r的意思是“原生字符串”  
  8. pattern = re.compile(r'hello')  
  9.    
  10. # 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None  
  11. match1 = pattern.match('hello world!')  
  12. match2 = pattern.match('helloo world!')  
  13. match3 = pattern.match('helllo world!')  
  14.   
  15. #如果match1匹配成功  
  16. if match1:  
  17.     # 使用Match获得分组信息  
  18.     print match1.group()  
  19. else:  
  20.     print 'match1匹配失败!'  
  21.   
  22.   
  23. #如果match2匹配成功  
  24. if match2:  
  25.     # 使用Match获得分组信息  
  26.     print match2.group()  
  27. else:  
  28.     print 'match2匹配失败!'  
  29.   
  30.   
  31. #如果match3匹配成功  
  32. if match3:  
  33.     # 使用Match获得分组信息  
  34.     print match3.group()  
  35. else:  
  36.     print 'match3匹配失败!'  

可以看到控制台输出了匹配的三个结果:

下面来具体看看代码中的关键方法。

★ re.compile(strPattern[, flag]):

这个方法是Pattern类的工厂方法,用于将字符串形式的正则表达式编译为Pattern对象。

第二个参数flag是匹配模式,取值可以使用按位或运算符'|'表示同时生效,比如re.I | re.M。

另外,你也可以在regex字符串中指定模式,

比如re.compile('pattern', re.I | re.M)与re.compile('(?im)pattern')是等价的。

可选值有:

  •     re.I(全拼:IGNORECASE): 忽略大小写(括号内是完整写法,下同)
  •    re.M(全拼:MULTILINE): 多行模式,改变'^'和'$'的行为(参见上图)
  •     re.S(全拼:DOTALL): 点任意匹配模式,改变'.'的行为
  •     re.L(全拼:LOCALE): 使预定字符类 \w \W \b \B \s \S 取决于当前区域设定
  •     re.U(全拼:UNICODE): 使预定字符类 \w \W \b \B \s \S \d \D 取决于unicode定义的字符属性
  •     re.X(全拼:VERBOSE): 详细模式。这个模式下正则表达式可以是多行,忽略空白字符,并可以加入注释。


以下两个正则表达式是等价的:

[python]  view plain copy
  1. # -*- coding: utf-8 -*-  
  2. #两个等价的re匹配,匹配一个小数  
  3. import re  
  4.   
  5. a = re.compile(r"""\d +  # the integral part 
  6.                    \.    # the decimal point 
  7.                    \d *  # some fractional digits""", re.X)  
  8.   
  9. b = re.compile(r"\d+\.\d*")  
  10.   
  11. match11 = a.match('3.1415')  
  12. match12 = a.match('33')  
  13. match21 = b.match('3.1415')  
  14. match22 = b.match('33')   
  15.   
  16. if match11:  
  17.     # 使用Match获得分组信息  
  18.     print match11.group()  
  19. else:  
  20.     print u'match11不是小数'  
  21.       
  22. if match12:  
  23.     # 使用Match获得分组信息  
  24.     print match12.group()  
  25. else:  
  26.     print u'match12不是小数'  
  27.       
  28. if match21:  
  29.     # 使用Match获得分组信息  
  30.     print match21.group()  
  31. else:  
  32.     print u'match21不是小数'  
  33.   
  34. if match22:  
  35.     # 使用Match获得分组信息  
  36.     print match22.group()  
  37. else:  
  38.     print u'match22不是小数'  

re提供了众多模块方法用于完成正则表达式的功能。

这些方法可以使用Pattern实例的相应方法替代,唯一的好处是少写一行re.compile()代码,

但同时也无法复用编译后的Pattern对象。

这些方法将在Pattern类的实例方法部分一起介绍。

如一开始的hello实例可以简写为:

[html]  view plain copy
  1. # -*- coding: utf-8 -*-  
  2. #一个简单的re实例,匹配字符串中的hello字符串  
  3. import re  
  4.   
  5. m = re.match(r'hello', 'hello world!')  
  6. print m.group()  

re模块还提供了一个方法escape(string),用于将string中的正则表达式元字符如*/+/?等之前加上转义符再返回


2.2. Match

Match对象是一次匹配的结果,包含了很多关于此次匹配的信息,可以使用Match提供的可读属性或方法来获取这些信息。

属性:

  1. string: 匹配时使用的文本。
  2. re: 匹配时使用的Pattern对象。
  3. pos: 文本中正则表达式开始搜索的索引。值与Pattern.match()和Pattern.seach()方法的同名参数相同。
  4. endpos: 文本中正则表达式结束搜索的索引。值与Pattern.match()和Pattern.seach()方法的同名参数相同。
  5. lastindex: 最后一个被捕获的分组在文本中的索引。如果没有被捕获的分组,将为None。
  6. lastgroup: 最后一个被捕获的分组的别名。如果这个分组没有别名或者没有被捕获的分组,将为None。

方法:

  1. group([group1, …]):
    获得一个或多个分组截获的字符串;指定多个参数时将以元组形式返回。group1可以使用编号也可以使用别名;编号0代表整个匹配的子串;不填写参数时,返回group(0);没有截获字符串的组返回None;截获了多次的组返回最后一次截获的子串。
  2. groups([default]): 
    以元组形式返回全部分组截获的字符串。相当于调用group(1,2,…last)。default表示没有截获字符串的组以这个值替代,默认为None。
  3. groupdict([default]):
    返回以有别名的组的别名为键、以该组截获的子串为值的字典,没有别名的组不包含在内。default含义同上。
  4. start([group]): 
    返回指定的组截获的子串在string中的起始索引(子串第一个字符的索引)。group默认值为0。
  5. end([group]):
    返回指定的组截获的子串在string中的结束索引(子串最后一个字符的索引+1)。group默认值为0。
  6. span([group]):
    返回(start(group), end(group))。
  7. expand(template): 
    将匹配到的分组代入template中然后返回。template中可以使用\id或\g<id>、\g<name>引用分组,但不能使用编号0。\id与\g<id>是等价的;但\10将被认为是第10个分组,如果你想表达\1之后是字符'0',只能使用\g<1>0。
下面来用一个py实例输出所有的内容加深理解:

[python]  view plain copy
  1. # -*- coding: utf-8 -*-  
  2. #一个简单的match实例  
  3.   
  4. import re  
  5. # 匹配如下内容:单词+空格+单词+任意字符  
  6. m = re.match(r'(\w+) (\w+)(?P<sign>.*)''hello world!')  
  7.   
  8. print "m.string:", m.string  
  9. print "m.re:", m.re  
  10. print "m.pos:", m.pos  
  11. print "m.endpos:", m.endpos  
  12. print "m.lastindex:", m.lastindex  
  13. print "m.lastgroup:", m.lastgroup  
  14.   
  15. print "m.group():", m.group()  
  16. print "m.group(1,2):", m.group(12)  
  17. print "m.groups():", m.groups()  
  18. print "m.groupdict():", m.groupdict()  
  19. print "m.start(2):", m.start(2)  
  20. print "m.end(2):", m.end(2)  
  21. print "m.span(2):", m.span(2)  
  22. print r"m.expand(r'\g<2> \g<1>\g<3>'):", m.expand(r'\2 \1\3')  
  23.    
  24. ### output ###  
  25. # m.string: hello world!  
  26. # m.re: <_sre.SRE_Pattern object at 0x016E1A38>  
  27. # m.pos: 0  
  28. # m.endpos: 12  
  29. # m.lastindex: 3  
  30. # m.lastgroup: sign  
  31. # m.group(1,2): ('hello', 'world')  
  32. # m.groups(): ('hello', 'world', '!')  
  33. # m.groupdict(): {'sign': '!'}  
  34. # m.start(2): 6  
  35. # m.end(2): 11  
  36. # m.span(2): (6, 11)  
  37. # m.expand(r'\2 \1\3'): world hello!  


2.3. Pattern

Pattern对象是一个编译好的正则表达式,通过Pattern提供的一系列方法可以对文本进行匹配查找。

Pattern不能直接实例化,必须使用re.compile()进行构造,也就是re.compile()返回的对象。

Pattern提供了几个可读属性用于获取表达式的相关信息:

  1. pattern: 编译时用的表达式字符串。
  2. flags: 编译时用的匹配模式。数字形式。
  3. groups: 表达式中分组的数量。
  4. groupindex: 以表达式中有别名的组的别名为键、以该组对应的编号为值的字典,没有别名的组不包含在内。
可以用下面这个例子查看pattern的属性:

[python]  view plain copy
  1. # -*- coding: utf-8 -*-  
  2. #一个简单的pattern实例  
  3.   
  4. import re  
  5. p = re.compile(r'(\w+) (\w+)(?P<sign>.*)', re.DOTALL)  
  6.    
  7. print "p.pattern:", p.pattern  
  8. print "p.flags:", p.flags  
  9. print "p.groups:", p.groups  
  10. print "p.groupindex:", p.groupindex  
  11.    
  12. ### output ###  
  13. # p.pattern: (\w+) (\w+)(?P<sign>.*)  
  14. # p.flags: 16  
  15. # p.groups: 3  
  16. # p.groupindex: {'sign': 3}  

下面重点介绍一下pattern的实例方法及其使用。

1.match

match(string[, pos[, endpos]]) | re.match(pattern, string[, flags]):

这个方法将从string的pos下标处起尝试匹配pattern;

如果pattern结束时仍可匹配,则返回一个Match对象;

如果匹配过程中pattern无法匹配,或者匹配未结束就已到达endpos,则返回None。

pos和endpos的默认值分别为0和len(string);

re.match()无法指定这两个参数,参数flags用于编译pattern时指定匹配模式。

注意:这个方法并不是完全匹配。

当pattern结束时若string还有剩余字符,仍然视为成功。

想要完全匹配,可以在表达式末尾加上边界匹配符'$'。

下面来看一个Match的简单案例:

[python]  view plain copy
  1. # encoding: UTF-8  
  2. import re  
  3.    
  4. # 将正则表达式编译成Pattern对象  
  5. pattern = re.compile(r'hello')  
  6.    
  7. # 使用Pattern匹配文本,获得匹配结果,无法匹配时将返回None  
  8. match = pattern.match('hello world!')  
  9.    
  10. if match:  
  11.     # 使用Match获得分组信息  
  12.     print match.group()  
  13.    
  14. ### 输出 ###  
  15. # hello  



2.search
search(string[, pos[, endpos]]) | re.search(pattern, string[, flags]): 
这个方法用于查找字符串中可以匹配成功的子串。

从string的pos下标处起尝试匹配pattern,

如果pattern结束时仍可匹配,则返回一个Match对象;

若无法匹配,则将pos加1后重新尝试匹配;

直到pos=endpos时仍无法匹配则返回None。

pos和endpos的默认值分别为0和len(string));

re.search()无法指定这两个参数,参数flags用于编译pattern时指定匹配模式。

那么它和match有什么区别呢?

match()函数只检测re是不是在string的开始位置匹配,

search()会扫描整个string查找匹配,


match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回none
例如:
print(re.match(‘super’, ‘superstition’).span())

会返回(0, 5)

print(re.match(‘super’, ‘insuperable’))

则返回None

search()会扫描整个字符串并返回第一个成功的匹配
例如:

print(re.search(‘super’, ‘superstition’).span())

返回(0, 5)
print(re.search(‘super’, ‘insuperable’).span())

返回(2, 7)

看一个search的实例:

[python]  view plain copy
  1. # -*- coding: utf-8 -*-  
  2. #一个简单的search实例  
  3.   
  4. import re  
  5.    
  6. # 将正则表达式编译成Pattern对象  
  7. pattern = re.compile(r'world')  
  8.    
  9. # 使用search()查找匹配的子串,不存在能匹配的子串时将返回None  
  10. # 这个例子中使用match()无法成功匹配  
  11. match = pattern.search('hello world!')  
  12.    
  13. if match:  
  14.     # 使用Match获得分组信息  
  15.     print match.group()  
  16.    
  17. ### 输出 ###  
  18. # world  



3.split

split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):
按照能够匹配的子串将string分割后返回列表。

maxsplit用于指定最大分割次数,不指定将全部分割。

[python]  view plain copy
  1. import re  
  2.    
  3. p = re.compile(r'\d+')  
  4. print p.split('one1two2three3four4')  
  5.    
  6. ### output ###  
  7. # ['one', 'two', 'three', 'four', '']  


4.findall

findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):
搜索string,以列表形式返回全部能匹配的子串。

[python]  view plain copy
  1. import re  
  2.    
  3. p = re.compile(r'\d+')  
  4. print p.findall('one1two2three3four4')  
  5.    
  6. ### output ###  
  7. # ['1', '2', '3', '4']  


5.finditer

finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]):
搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器。

[html]  view plain copy
  1. import re  
  2.    
  3. p = re.compile(r'\d+')  
  4. for m in p.finditer('one1two2three3four4'):  
  5.     print m.group(),  
  6.    
  7. ### output ###  
  8. # 1 2 3 4  

6.sub

sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]):
使用repl替换string中每一个匹配的子串后返回替换后的字符串。 
当repl是一个字符串时,可以使用\id或\g<id>、\g<name>引用分组,但不能使用编号0。 
当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。 
count用于指定最多替换次数,不指定时全部替换。

[python]  view plain copy
  1. import re  
  2.    
  3. p = re.compile(r'(\w+) (\w+)')  
  4. s = 'i say, hello world!'  
  5.    
  6. print p.sub(r'\2 \1', s)  
  7.    
  8. def func(m):  
  9.     return m.group(1).title() + ' ' + m.group(2).title()  
  10.    
  11. print p.sub(func, s)  
  12.    
  13. ### output ###  
  14. # say i, world hello!  
  15. # I Say, Hello World!  

7.subn

subn(repl, string[, count]) |re.sub(pattern, repl, string[, count]):
返回 (sub(repl, string[, count]), 替换次数)。

[python]  view plain copy
  1. import re  
  2.    
  3. p = re.compile(r'(\w+) (\w+)')  
  4. s = 'i say, hello world!'  
  5.    
  6. print p.subn(r'\2 \1', s)  
  7.    
  8. def func(m):  
  9.     return m.group(1).title() + ' ' + m.group(2).title()  
  10.    
  11. print p.subn(func, s)  
  12.    
  13. ### output ###  
  14. # ('say i, world hello!', 2)  
  15. # ('I Say, Hello World!', 2)  

至此,Python的正则表达式基本介绍就算是完成了^_^
 

[Python]网络爬虫(八):糗事百科的网络爬虫(v0.2)源码及解析

分类: Python 爬虫   1208人阅读  评论(7)  收藏  举报

项目内容:

用Python写的糗事百科的网络爬虫。

使用方法:

新建一个Bug.py文件,然后将代码复制到里面后,双击运行。

程序功能:

在命令提示行中浏览糗事百科。

原理解释:

首先,先浏览一下糗事百科的主页:http://www.qiushibaike.com/hot/page/1

可以看出来,链接中page/后面的数字就是对应的页码,记住这一点为以后的编写做准备。

然后,右击查看页面源码:

观察发现,每一个段子都用div标记,其中class必为content,title是发帖时间,我们只需要用正则表达式将其“扣”出来就可以了。

明白了原理之后,剩下的就是正则表达式的内容了,可以参照这篇博文:

http://blog.csdn.net/wxg694175346/article/details/8929576


运行效果:




[python]  view plain copy
  1. # -*- coding: utf-8 -*-  
  2. #---------------------------------------  
  3. #   程序:糗百爬虫  
  4. #   版本:0.2  
  5. #   作者:why  
  6. #   日期:2013-05-15  
  7. #   语言:Python 2.7  
  8. #   操作:输入quit退出阅读糗事百科  
  9. #   功能:按下回车依次浏览今日的糗百热点  
  10. #   更新:解决了命令提示行下乱码的问题  
  11. #---------------------------------------  
  12.    
  13. import urllib2  
  14. import urllib  
  15. import re  
  16. import thread  
  17. import time  
  18.   
  19. #----------- 处理页面上的各种标签 -----------  
  20. class HTML_Tool:  
  21.     # 用非 贪婪模式 匹配 \t 或者 \n 或者 空格 或者 超链接 或者 图片  
  22.     BgnCharToNoneRex = re.compile("(\t|\n| |<a.*?>|<img.*?>)")  
  23.       
  24.     # 用非 贪婪模式 匹配 任意<>标签  
  25.     EndCharToNoneRex = re.compile("<.*?>")  
  26.   
  27.     # 用非 贪婪模式 匹配 任意<p>标签  
  28.     BgnPartRex = re.compile("<p.*?>")  
  29.     CharToNewLineRex = re.compile("(<br/>|</p>|<tr>|<div>|</div>)")  
  30.     CharToNextTabRex = re.compile("<td>")  
  31.   
  32.     # 将一些html的符号实体转变为原始符号  
  33.     replaceTab = [("<","<"),(">",">"),("&","&"),("&","\""),(" "," ")]  
  34.       
  35.     def Replace_Char(self,x):  
  36.         x = self.BgnCharToNoneRex.sub("",x)  
  37.         x = self.BgnPartRex.sub("\n    ",x)  
  38.         x = self.CharToNewLineRex.sub("\n",x)  
  39.         x = self.CharToNextTabRex.sub("\t",x)  
  40.         x = self.EndCharToNoneRex.sub("",x)  
  41.   
  42.         for t in self.replaceTab:  
  43.             x = x.replace(t[0],t[1])  
  44.         return x  
  45. #----------- 处理页面上的各种标签 -----------  
  46.   
  47.   
  48. #----------- 加载处理糗事百科 -----------  
  49. class HTML_Model:  
  50.       
  51.     def __init__(self):  
  52.         self.page = 1  
  53.         self.pages = []  
  54.         self.myTool = HTML_Tool()  
  55.         self.enable = False  
  56.   
  57.     # 将所有的段子都扣出来,添加到列表中并且返回列表  
  58.     def GetPage(self,page):  
  59.         myUrl = "http://m.qiushibaike.com/hot/page/" + page  
  60.         myResponse  = urllib2.urlopen(myUrl)  
  61.         myPage = myResponse.read()  
  62.         #encode的作用是将unicode编码转换成其他编码的字符串  
  63.         #decode的作用是将其他编码的字符串转换成unicode编码  
  64.         unicodePage = myPage.decode("utf-8")  
  65.   
  66.         # 找出所有class="content"的div标记  
  67.         #re.S是任意匹配模式,也就是.可以匹配换行符  
  68.         myItems = re.findall('<div.*?class="content".*?title="(.*?)">(.*?)</div>',unicodePage,re.S)  
  69.         items = []  
  70.         for item in myItems:  
  71.             # item 中第一个是div的标题,也就是时间  
  72.             # item 中第二个是div的内容,也就是内容  
  73.             items.append([item[0].replace("\n",""),item[1].replace("\n","")])  
  74.         return items  
  75.   
  76.     # 用于加载新的段子  
  77.     def LoadPage(self):  
  78.         # 如果用户未输入quit则一直运行  
  79.         while self.enable:  
  80.             # 如果pages数组中的内容小于2个  
  81.             if len(self.pages) < 2:  
  82.                 try:  
  83.                     # 获取新的页面中的段子们  
  84.                     myPage = self.GetPage(str(self.page))  
  85.                     self.page += 1  
  86.                     self.pages.append(myPage)  
  87.                 except:  
  88.                     print '无法链接糗事百科!'  
  89.             else:  
  90.                 time.sleep(1)  
  91.           
  92.     def ShowPage(self,q,page):  
  93.         for items in q:  
  94.             print u'第%d页' % page , items[0]  
  95.             print self.myTool.Replace_Char(items[1])  
  96.             myInput = raw_input()  
  97.             if myInput == "quit":  
  98.                 self.enable = False  
  99.                 break  
  100.           
  101.     def Start(self):  
  102.         self.enable = True  
  103.         page = self.page  
  104.   
  105.         print u'正在加载中请稍候......'  
  106.           
  107.         # 新建一个线程在后台加载段子并存储  
  108.         thread.start_new_thread(self.LoadPage,())  
  109.           
  110.         #----------- 加载处理糗事百科 -----------  
  111.         while self.enable:  
  112.             # 如果self的page数组中存有元素  
  113.             if self.pages:  
  114.                 nowPage = self.pages[0]  
  115.                 del self.pages[0]  
  116.                 self.ShowPage(nowPage,page)  
  117.                 page += 1  
  118.   
  119.   
  120. #----------- 程序的入口处 -----------  
  121. print u""" 
  122. --------------------------------------- 
  123.    程序:糗百爬虫 
  124.    版本:0.1 
  125.    作者:why 
  126.    日期:2013-05-15 
  127.    语言:Python 2.7 
  128.    操作:输入quit退出阅读糗事百科 
  129.    功能:按下回车依次浏览今日的糗百热点 
  130. --------------------------------------- 
  131. """  
  132.   
  133.   
  134. print u'请按下回车浏览今日的糗百内容:'  
  135. raw_input(' ')  
  136. myModel = HTML_Model()  
  137. myModel.Start() 
 

[Python]网络爬虫(九):百度贴吧的网络爬虫(v0.4)源码及解析

分类: 爬虫 Python   1361人阅读  评论(10)  收藏  举报

百度贴吧的爬虫制作和糗百的爬虫制作原理基本相同,都是通过查看源码扣出关键数据,然后将其存储到本地txt文件。

项目内容:

用Python写的百度贴吧的网络爬虫。

使用方法:

新建一个BugBaidu.py文件,然后将代码复制到里面后,双击运行。

程序功能:

将贴吧中楼主发布的内容打包txt存储到本地。

原理解释:

首先,先浏览一下某一条贴吧,点击只看楼主并点击第二页之后url发生了一点变化,变成了:

http://tieba.baidu.com/p/2296712428?see_lz=1&pn=1

可以看出来,see_lz=1是只看楼主,pn=1是对应的页码,记住这一点为以后的编写做准备。

这就是我们需要利用的url。

接下来就是查看页面源码。

首先把题目抠出来存储文件的时候会用到。

可以看到百度使用gbk编码,标题使用h1标记:

[html]  view plain copy
  1. <h1 class="core_title_txt" title="【原创】时尚首席(关于时尚,名利,事业,爱情,励志)">【原创】时尚首席(关于时尚,名利,事业,爱情,励志)</h1>  

同样,正文部分用div和class综合标记,接下来要做的只是用正则表达式来匹配即可。

运行截图:

生成的txt文件:



[python]  view plain copy
  1. # -*- coding: utf-8 -*-  
  2. #---------------------------------------  
  3. #   程序:百度贴吧爬虫  
  4. #   版本:0.5  
  5. #   作者:why  
  6. #   日期:2013-05-16  
  7. #   语言:Python 2.7  
  8. #   操作:输入网址后自动只看楼主并保存到本地文件  
  9. #   功能:将楼主发布的内容打包txt存储到本地。  
  10. #---------------------------------------  
  11.    
  12. import string  
  13. import urllib2  
  14. import re  
  15.   
  16. #----------- 处理页面上的各种标签 -----------  
  17. class HTML_Tool:  
  18.     # 用非 贪婪模式 匹配 \t 或者 \n 或者 空格 或者 超链接 或者 图片  
  19.     BgnCharToNoneRex = re.compile("(\t|\n| |<a.*?>|<img.*?>)")  
  20.       
  21.     # 用非 贪婪模式 匹配 任意<>标签  
  22.     EndCharToNoneRex = re.compile("<.*?>")  
  23.   
  24.     # 用非 贪婪模式 匹配 任意<p>标签  
  25.     BgnPartRex = re.compile("<p.*?>")  
  26.     CharToNewLineRex = re.compile("(<br/>|</p>|<tr>|<div>|</div>)")  
  27.     CharToNextTabRex = re.compile("<td>")  
  28.   
  29.     # 将一些html的符号实体转变为原始符号  
  30.     replaceTab = [("<","<"),(">",">"),("&","&"),("&","\""),(" "," ")]  
  31.       
  32.     def Replace_Char(self,x):  
  33.         x = self.BgnCharToNoneRex.sub("",x)  
  34.         x = self.BgnPartRex.sub("\n    ",x)  
  35.         x = self.CharToNewLineRex.sub("\n",x)  
  36.         x = self.CharToNextTabRex.sub("\t",x)  
  37.         x = self.EndCharToNoneRex.sub("",x)  
  38.   
  39.         for t in self.replaceTab:    
  40.             x = x.replace(t[0],t[1])    
  41.         return x    
  42.       
  43. class Baidu_Spider:  
  44.     # 申明相关的属性  
  45.     def __init__(self,url):    
  46.         self.myUrl = url + '?see_lz=1'  
  47.         self.datas = []  
  48.         self.myTool = HTML_Tool()  
  49.         print u'已经启动百度贴吧爬虫,咔嚓咔嚓'  
  50.     
  51.     # 初始化加载页面并将其转码储存  
  52.     def baidu_tieba(self):  
  53.         # 读取页面的原始信息并将其从gbk转码  
  54.         myPage = urllib2.urlopen(self.myUrl).read().decode("gbk")  
  55.         # 计算楼主发布内容一共有多少页  
  56.         endPage = self.page_counter(myPage)  
  57.         # 获取该帖的标题  
  58.         title = self.find_title(myPage)  
  59.         print u'文章名称:' + title  
  60.         # 获取最终的数据  
  61.         self.save_data(self.myUrl,title,endPage)  
  62.   
  63.     #用来计算一共有多少页  
  64.     def page_counter(self,myPage):  
  65.         # 匹配 "共有<span class="red">12</span>页" 来获取一共有多少页  
  66.         myMatch = re.search(r'class="red">(\d+?)</span>', myPage, re.S)  
  67.         if myMatch:    
  68.             endPage = int(myMatch.group(1))  
  69.             print u'爬虫报告:发现楼主共有%d页的原创内容' % endPage  
  70.         else:  
  71.             endPage = 0  
  72.             print u'爬虫报告:无法计算楼主发布内容有多少页!'  
  73.         return endPage  
  74.   
  75.     # 用来寻找该帖的标题  
  76.     def find_title(self,myPage):  
  77.         # 匹配 <h1 class="core_title_txt" title="">xxxxxxxxxx</h1> 找出标题  
  78.         myMatch = re.search(r'<h1.*?>(.*?)</h1>', myPage, re.S)  
  79.         title = u'暂无标题'  
  80.         if myMatch:  
  81.             title  = myMatch.group(1)  
  82.         else:  
  83.             print u'爬虫报告:无法加载文章标题!'  
  84.         # 文件名不能包含以下字符: \ / : * ? " < > |  
  85.         title = title.replace('\\','').replace('/','').replace(':','').replace('*','').replace('?','').replace('"','').replace('>','').replace('<','').replace('|','')  
  86.         return title  
  87.   
  88.   
  89.     # 用来存储楼主发布的内容  
  90.     def save_data(self,url,title,endPage):  
  91.         # 加载页面数据到数组中  
  92.         self.get_data(url,endPage)  
  93.         # 打开本地文件  
  94.         f = open(title+'.txt','w+')  
  95.         f.writelines(self.datas)  
  96.         f.close()  
  97.         print u'爬虫报告:文件已下载到本地并打包成txt文件'  
  98.         print u'请按任意键退出...'  
  99.         raw_input();  
  100.   
  101.     # 获取页面源码并将其存储到数组中  
  102.     def get_data(self,url,endPage):  
  103.         url = url + '&pn='  
  104.         for i in range(1,endPage+1):  
  105.             print u'爬虫报告:爬虫%d号正在加载中...' % i  
  106.             myPage = urllib2.urlopen(url + str(i)).read()  
  107.             # 将myPage中的html代码处理并存储到datas里面  
  108.             self.deal_data(myPage.decode('gbk'))  
  109.               
  110.   
  111.     # 将内容从页面代码中抠出来  
  112.     def deal_data(self,myPage):  
  113.         myItems = re.findall('id="post_content.*?>(.*?)</div>',myPage,re.S)  
  114.         for item in myItems:  
  115.             data = self.myTool.Replace_Char(item.replace("\n","").encode('gbk'))  
  116.             self.datas.append(data+'\n')  
  117.   
  118.   
  119.   
  120. #-------- 程序入口处 ------------------  
  121. print u"""#--------------------------------------- 
  122. #   程序:百度贴吧爬虫 
  123. #   版本:0.5 
  124. #   作者:why 
  125. #   日期:2013-05-16 
  126. #   语言:Python 2.7 
  127. #   操作:输入网址后自动只看楼主并保存到本地文件 
  128. #   功能:将楼主发布的内容打包txt存储到本地。 
  129. #--------------------------------------- 
  130. """  
  131.   
  132. # 以某小说贴吧为例子  
  133. # bdurl = 'http://tieba.baidu.com/p/2296712428?see_lz=1&pn=1'  
  134.   
  135. print u'请输入贴吧的地址最后的数字串:'  
  136. bdurl = 'http://tieba.baidu.com/p/' + str(raw_input(u'http://tieba.baidu.com/p/'))   
  137.   
  138. #调用  
  139. mySpider = Baidu_Spider(bdurl)  
  140. mySpider.baidu_tieba()  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值