博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
一个完整的大作业
阅读量:7243 次
发布时间:2019-06-29

本文共 4027 字,大约阅读时间需要 13 分钟。

 

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

1.使用方法:

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

2.程序功能:

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

3.原理解释:

首先,先浏览一下某一条贴吧,点击只看楼主并点击第二页之后url发生了一点变化,变成了:http://tieba.baidu.com/p/2296712428?see_lz=1&pn=1可以看出来,see_lz=1是只看楼主,pn=1是对应的页码,记住这一点为以后的编写做准备。这就是我们需要利用的url。接下来就是查看页面源码。首先把题目抠出来存储文件的时候会用到。可以看到百度使用gbk编码,标题使用h1标记:

4.运行截图:

5.生成的txt文件:

 

 

6.源代码展示:

# -*- coding: utf-8 -*- import string import urllib2 import re #----------- 处理页面上的各种标签 ----------- class HTML_Tool:   # 用非 贪婪模式 匹配 \t 或者 \n 或者 空格 或者 超链接 或者 图片   BgnCharToNoneRex = re.compile("(\t|\n| |
|
)") # 用非 贪婪模式 匹配 任意<>标签 EndCharToNoneRex = re.compile("<.*?>") # 用非 贪婪模式 匹配 任意

标签 BgnPartRex = re.compile("

") CharToNewLineRex = re.compile("(
|

||
|
)") CharToNextTabRex = re.compile("") # 将一些html的符号实体转变为原始符号 replaceTab = [("<","<"),(">",">"),("&","&"),("&","\""),(" "," ")] def Replace_Char(self,x): x = self.BgnCharToNoneRex.sub("",x) x = self.BgnPartRex.sub("\n ",x) x = self.CharToNewLineRex.sub("\n",x) x = self.CharToNextTabRex.sub("\t",x) x = self.EndCharToNoneRex.sub("",x) for t in self.replaceTab: x = x.replace(t[0],t[1]) return x class Baidu_Spider: # 申明相关的属性 def __init__(self,url): self.myUrl = url + '?see_lz=1' self.datas = [] self.myTool = HTML_Tool() print u'已经启动百度贴吧爬虫,咔嚓咔嚓' # 初始化加载页面并将其转码储存 def baidu_tieba(self): # 读取页面的原始信息并将其从gbk转码 myPage = urllib2.urlopen(self.myUrl).read().decode("gbk") # 计算楼主发布内容一共有多少页 endPage = self.page_counter(myPage) # 获取该帖的标题 title = self.find_title(myPage) print u'文章名称:' + title # 获取最终的数据 self.save_data(self.myUrl,title,endPage) #用来计算一共有多少页 def page_counter(self,myPage): # 匹配 "共有
12页" 来获取一共有多少页 myMatch = re.search(r'class="red">(\d+?)', myPage, re.S) if myMatch: endPage = int(myMatch.group(1)) print u'爬虫报告:发现楼主共有%d页的原创内容' % endPage else: endPage = 0 print u'爬虫报告:无法计算楼主发布内容有多少页!' return endPage # 用来寻找该帖的标题 def find_title(self,myPage): # 匹配

xxxxxxxxxx

找出标题 myMatch = re.search(r"
(.*?)', myPage, re.S) title = u'暂无标题' if myMatch: title = myMatch.group(1) else: print u'爬虫报告:无法加载文章标题!' # 文件名不能包含以下字符: \ / : * ? " < > | title = title.replace('\\','').replace('/','').replace(':','').replace('*','').replace('?','').replace('"','').replace('>','').replace('<','').replace('|','') return title # 用来存储楼主发布的内容 def save_data(self,url,title,endPage): # 加载页面数据到数组中 self.get_data(url,endPage) # 打开本地文件 f = open(title+'.txt','w+') f.writelines(self.datas) f.close() print u'爬虫报告:文件已下载到本地并打包成txt文件' print u'请按任意键退出...' raw_input(); # 获取页面源码并将其存储到数组中 def get_data(self,url,endPage): url = url + '&pn=' for i in range(1,endPage+1): print u'爬虫报告:爬虫%d号正在加载中...' % i myPage = urllib2.urlopen(url + str(i)).read() # 将myPage中的html代码处理并存储到datas里面 self.deal_data(myPage.decode('gbk')) # 将内容从页面代码中抠出来 def deal_data(self,myPage): myItems = re.findall('id="post_content.*?>(.*?)',myPage,re.S) for item in myItems: data = self.myTool.Replace_Char(item.replace("\n","").encode('gbk')) self.datas.append(data+'\n')
#-------- 程序入口处 ------------------ # 以某小说贴吧为例子 # bdurl = 'http://tieba.baidu.com/p/2296712428?see_lz=1&pn=1' print u'请输入贴吧的地址最后的数字串:' bdurl = 'http://tieba.baidu.com/p/' + str(raw_input(u'http://tieba.baidu.com/p/'))  #调用 mySpider = Baidu_Spider(bdurl) mySpider.baidu_tieba()

7.生成词云的原代码

#coding:utf-8import jiebafrom wordcloud import WordCloudimport matplotlib.pyplot as plttext =open(r"C:\Users\Administrator\Desktop\sheng.txt",'r').read()wordlist = jieba.cut(text,cut_all=True)wl_split = "/".join(wordlist)mywc = WordCloud().generate(text)plt.imshow(mywc)plt.axis("off")plt.show()

      这是我对Python爬虫的理解,谢谢老师的教育和指导。这是我工作前,学到最实用的课程。非常感谢。

 

转载于:https://www.cnblogs.com/huanglinsheng/p/7769019.html

你可能感兴趣的文章
笨办法学C 练习4:Valgrind 介绍
查看>>
超详细cordova环境配置(windows)及实例
查看>>
关于浮动float
查看>>
进入2016 -- 回顾我走过的编程之路
查看>>
SegmentFault D-Day 北京场「iOS」 活动回顾
查看>>
★★★★盲转接业务的sipp脚本实现
查看>>
Leetcode-Two Sum
查看>>
汉语言处理包 HanLP 1.7.3 发布,常规维护版本
查看>>
滑屏组件----slide
查看>>
Android 凉了?聊聊Android的出路,架构必备技术
查看>>
如何用纯 CSS 创作一个苹果系统的相册图标
查看>>
货拉拉完成 3 亿美元 D 轮融资,2018 年全年业务量增长将近 200% ...
查看>>
观点 | 阿里资深技术专家:优秀的数据库存储引擎应具备哪些能力? ...
查看>>
Golang AES加密
查看>>
Android之greenDao使用
查看>>
Ceph Storage Cluster(CEPH存储集群) Configuration配置
查看>>
mysql面试题分组并合并列
查看>>
如何用纯 CSS 创作一台拍立得照相机
查看>>
洛谷 P3369 BZOJ 3224 【模板】普通平衡树(Treap/SBT)
查看>>
Mybatis - 分页拦截器
查看>>