python抓取网页内容并进行语音播报的方法
作者:jupeizhong 发布时间:2021-03-08 14:02:53
标签:python,语音,播报
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是由程序生成的。
来源:https://blog.csdn.net/jupeizhong/article/details/51231935


猜你喜欢
- 使用matplotlib创建百分比堆积柱状图的思路与堆积柱状图类似,只不过bottom参数累计的不是数值而是百分比,因此,需要事先计算每组柱
- 下面是IN条件运算符的SQL语句:SELECT column1, SUM(column2) FROM&nbs
- 本文实例讲述了php设计模式之适配器模式。分享给大家供大家参考,具体如下:星际的很多兵种,都有至少一项特殊技能。而且有些兵种的技能是相同的,
- 比较好的地方就是js数组的操作,不重复的数组id显示,完美实现。<script language="JavaScript&q
- 区别IE6与FF:background:orange;*background:blue;区别IE6与IE7:background:green
- 函数没有SQL的可移植性强 能运行在多个系统上的代码称为可移植的(portable)。相对来说,多数SQL语句是可移植的,在SQL实现之间有
- 我就废话不多说了,大家还是直接看代码吧!import socketimport sysimport timeimport structHOS
- 实例076:做函数题目:编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数1/1+1/3+.
- 一. 背景介绍当集团的MySQL数据库实例数达到2000+、MHA集群规模数百个时,对MHA的及时、高效管理是DBA必须面对的一个挑战。MH
- 前言说到运算符重载相信大家都不陌生,运算符重载的作用是让用户定义的对象使用中缀运算符(如 + 和 |)或一元运算符(如 - 和 ~)。说得宽
- 1. 序网页弹框是个很常见的功能,比如需要告知用户消息的时候 (Alert),需要用户进行确认的时候 (Confirm),需要用户补充一点信
- 目录一、前言二、使用1.@Component2.compued、data、methods3.@props4.@watch5.@emit三 、
- 本文为大家分享了python字典DICT类型合并的方法,供大家参考,具体内容如下我要的字典的键值有些是数据库中表的字段名, 但是有些却不是,
- 本文实例讲述了gearman+mysql方式实现持久化操作。分享给大家供大家参考,具体如下:1、为什么要持久化?gearman的job se
- 本文实例讲述了PHP实现数组根据某个字段进行水平合并,横向合并。分享给大家供大家参考,具体如下:PHP数组水平合并,横向合并,两条数据合并成
- 1、 在sublime text的官网下载,是适合自己系统的版本。官网地址:https://www.sublimetext.com/32、安
- 创建类Python 类使用 class 关键字来创建。简单的类的声明可以是关键字后紧跟类名:class ClassName(bases):&
- 通过文件夹导入包要求每个目录下都有一个__init__.py文件,此文件可空白。也可不空。a@ubuntu:~/Desktop$ tree
- 引言:在机器学习还有深度学习中,经常会用到这几个函数,为了便于以后熟练使用,现在对这几个函数进行总结。(一)np.random.rand()
- git还原到某次commit并强制推送远程不可逆提交一、reset1.git log查看提交记录git log2.选择某次提交的commit