python抓取网页内容并进行语音播报的方法


Posted in Python onDecember 24, 2018

python2.7,下面是跑在window上的,稍作修改就可以跑在linux上。

实测win7和raspbian均可,且raspbian可以直接调用omxplayer命令进行播放。

利用百度的语音合成api进行语音播报,抓取的页面是北大未名BBS的十大。

先放抓取模块BDWM.py的代码:

# -*- coding: utf-8 -*-
import urllib2
import HTMLParser
 
class MyParser(HTMLParser.HTMLParser):
 def __init__(self):
 HTMLParser.HTMLParser.__init__(self) 
 self.nowtag = ''
 self.count = 0
 self.flag = False
 self.isLink = False
 self.count2 = 0
 self.dict = {}
 self.temp = ''
 def handle_starttag(self, tag, attrs):
 if tag == 'span':
  for key, value in attrs:
  if key == 'class' and ('Rank1AmongHisBoard' in value):
   self.count += 1
   if self.count < 11:
   self.flag = True
 if tag == 'a':
  self.isLink = True
 else:
  self.isLink = False
 def handle_data(self, data):
 if self.flag and self.isLink:
  self.count2 += 1
  if self.count2 == 1:
  self.temp = data
  if self.count2 == 3:
  self.flag = False
  self.count2 = 0
  self.dict[self.temp] = data 
 
res = urllib2.urlopen('https://www.bdwm.net/bbs/main0.php')
my = MyParser()
my.feed(res.read().decode("gbk"))
result = ''
str = " 版 "
str = str.decode('utf8')
for i in my.dict:
 result += i + str + my.dict[i] + '\n'
print result

F5运行,抓取结果如下:

>>> ======================= RESTART =======================
>>>
化学与分子工程学院 版 不喜欢做实验怎么办
三角地 版 烈士旅正在对对研究生会实施最高军事占领的
十六周年站庆 版 ★★毕业季 | 未名BBS历年纪念品特卖会★★
遗迹保卫 版 母校两日游,想借个饭卡
别问我是谁 版 遇到性骚扰,打电话跟男朋友倾诉……
美食天地 版 请问北大附近哪里有好吃的饺子
男孩子 版 被戴绿帽,万念俱灰!
鹊桥 版 医生mm征GG(#征男友#代征)
谈情说爱 版 # 感觉身边都是嘴上急着脱光但心里不急的人 #
北京大学研究生会 版 农园一层和自称“常代会”的占座女吵起来了(转载)(转载)

可以看到我们成功抓取到了未名BBS十大的版面信息与标题。

下面放语音播报模块,也是整个程序的入口:

# -*- coding: utf-8 -*-
'''
Author  : Peizhong Ju
Latest Update : 2016/4/21
Function : Use Baidu Voice API to speak
'''
import urllib, urllib2
import json
import ConfigParser
import BDWM
 
config = ConfigParser.ConfigParser()
config.readfp(open('config.ini'))
TOKEN = config.get('Baidu', 'token')
local = config.get('Dir', 'mp3')
words = ''
 
def GetVoice():
 text = urllib.quote(words)
 url = 'http://tsn.baidu.com/text2audio?tex=' + text + '&cuid=b888e32e868c&lan=zh&ctp=1&tok=' + TOKEN
 rep = urllib.urlretrieve(url, local)
 CheckError()
 
def GetAccessToken():
 client_id = config.get('Baidu', 'client_id')
 client_secret = config.get('Baidu', 'client_secret')
 rep = urllib2.urlopen('https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id='+client_id+'&client_secret='+client_secret)
 hjson = json.loads(rep.read())
 return hjson['access_token']
 
def CheckError():
 global TOKEN
 file_object = open(local)
 try:
  all_the_text = file_object.read()
  if (all_the_text[0] == '{'):
  hjson = json.loads(all_the_text)
  #print hjson['err_no']
  if (hjson['err_no'] == 502):
   print 'Getting new access token...'
   TOKEN = GetAccessToken()
   config.set('Baidu', 'token', TOKEN)
   config.write(open('config.ini', "r+"))
   GetVoice()
  else:
   print all_the_text
  else:
  print '[success] ' + words
 finally:
  file_object.close()
 
try:
 words = BDWM.result.encode('utf8')
 GetVoice()
 # use other software to play it
except Exception as e:
 print "ERROR!"
 print e

当中我们用到了config文件,便于记录和修改,格式如下:

[Baidu]
client_id = HWWuh7dee6EBSAvzrOGaGNvX
client_secret = G3PwLHC5aCN2TQn3GcYjhn3BmH6xgxtR
token = 24.533d59e6554d133ea6bf02125bc6fa30.2592000.1463760851.282335-5802050
 
[Dir]
mp3 = C:\Users\jupeizhong\Desktop\python2\baiduVoice\hello.mp3

其中token是由程序生成的。

以上这篇python抓取网页内容并进行语音播报的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python中的二叉树查找算法模块使用指南
Jul 04 Python
Windows系统配置python脚本开机启动的3种方法分享
Mar 10 Python
使用Django Form解决表单数据无法动态刷新的两种方法
Jul 14 Python
python使用SMTP发送qq或sina邮件
Oct 21 Python
Python3中的列表生成式、生成器与迭代器实例详解
Jun 11 Python
python实现下载pop3邮件保存到本地
Jun 19 Python
Python实现高斯函数的三维显示方法
Dec 29 Python
浅析PEP572: 海象运算符
Oct 15 Python
Django Channel实时推送与聊天的示例代码
Apr 30 Python
解决TensorFlow程序无限制占用GPU的方法
Jun 30 Python
详细分析Python collections工具库
Jul 16 Python
详解numpy.ndarray.reshape()函数的参数问题
Oct 13 Python
解决pyttsx3无法封装的问题
Dec 24 #Python
pyttsx3实现中文文字转语音的方法
Dec 24 #Python
python实现flappy bird游戏
Dec 24 #Python
Python爬虫实现获取动态gif格式搞笑图片的方法示例
Dec 24 #Python
python 在屏幕上逐字显示一行字的实例
Dec 24 #Python
python之Flask实现简单登录功能的示例代码
Dec 24 #Python
python实现逐个读取txt字符并修改
Dec 24 #Python
You might like
Laravel5.1自定义500错误页面示例
2016/10/09 PHP
PHP+Ajax实现的检测用户名功能简单示例
2019/02/12 PHP
PHP大文件切割上传并带进度条功能示例
2019/07/01 PHP
encode脚本和normal脚本混用的问题与解决方法
2007/03/08 Javascript
JS事件Event元素(兼容IE,Firefox,Chorme)
2012/11/01 Javascript
form表单中去掉默认的enter键提交并绑定js方法实现代码
2013/04/01 Javascript
ajax如何实现页面局部跳转与结果返回
2015/08/24 Javascript
深入解析jQuery中Deferred的deferred.promise()方法
2016/05/03 Javascript
jQuery插件pagination实现无刷新分页
2016/05/21 Javascript
把普通对象转换成json格式的对象的简单实例
2016/07/04 Javascript
jQuery实现定位滚动条位置
2016/08/05 Javascript
JavaScript数据结构与算法之基本排序算法定义与效率比较【冒泡、选择、插入排序】
2019/02/21 Javascript
vue轻量级框架无法获取到vue对象解决方法
2019/05/12 Javascript
Python中optparse模块使用浅析
2015/01/01 Python
Python实现国外赌场热门游戏Craps(双骰子)
2015/03/31 Python
python实现发送和获取手机短信验证码
2016/01/15 Python
python实现感知器
2017/12/19 Python
Tensorflow 同时载入多个模型的实例讲解
2018/07/27 Python
详解Python下Flask-ApScheduler快速指南
2018/11/04 Python
Python 虚拟空间的使用代码详解
2019/06/10 Python
Python 200行代码实现一个滑动验证码过程详解
2019/07/11 Python
在django中,关于session的通用设置方法
2019/08/06 Python
在jupyter notebook中调用.ipynb文件方式
2020/04/14 Python
canvas离屏技术与放大镜实现代码示例
2018/08/31 HTML / CSS
Nordgreen英国官网:斯堪的纳维亚设计师手表
2018/10/24 全球购物
英国奢侈品在线精品店:Hervia
2020/09/03 全球购物
个性大学生自我评价
2013/12/04 职场文书
幼儿园保教管理制度
2014/02/03 职场文书
产品开发计划书
2014/04/27 职场文书
节约用水标语
2014/06/11 职场文书
2014房屋登记授权委托书
2014/10/13 职场文书
批评与自我批评范文
2014/10/15 职场文书
士兵突击观后感
2015/06/16 职场文书
2015年食品安全宣传周活动总结
2015/07/09 职场文书
安全生产会议制度
2015/08/06 职场文书
《我的美好婚事》动画化决定纪念插画与先导PV公开
2022/04/06 日漫