python抓取網(wǎng)頁內(nèi)容并進行語音播報的方法
python2.7,下面是跑在window上的,稍作修改就可以跑在linux上。
實測win7和raspbian均可,且raspbian可以直接調(diào)用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運行,抓取結(jié)果如下:
>>> ======================= RESTART =======================
>>>
化學與分子工程學院 版 不喜歡做實驗怎么辦
三角地 版 烈士旅正在對對研究生會實施最高軍事占領(lǐng)的
十六周年站慶 版 ★★畢業(yè)季 | 未名BBS歷年紀念品特賣會★★
遺跡保衛(wèi) 版 母校兩日游,想借個飯卡
別問我是誰 版 遇到性騷擾,打電話跟男朋友傾訴……
美食天地 版 請問北大附近哪里有好吃的餃子
男孩子 版 ,萬念俱灰!
鵲橋 版 醫(yī)生mm征GG(#征男友#代征)
談情說愛 版 # 感覺身邊都是嘴上急著但心里不急的人 #
北京大學研究生會 版 農(nóng)園一層和自稱“常代會”的占座女吵起來了(轉(zhuǎn)載)(轉(zhuǎn)載)
可以看到我們成功抓取到了未名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抓取網(wǎng)頁內(nèi)容并進行語音播報的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Python編程實現(xiàn)使用線性回歸預(yù)測數(shù)據(jù)
這篇文章主要介紹了Python編程實現(xiàn)使用線性回歸預(yù)測數(shù)據(jù),具有一定借鑒價值,需要的朋友可以了解下。2017-12-12
Python實現(xiàn)獲取亂序列表排序后的新下標的示例
本文主要介紹了Python實現(xiàn)獲取亂序列表排序后的新下標的示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-04-04
python基礎(chǔ)教程之基本內(nèi)置數(shù)據(jù)類型介紹
在Python程序中,每個數(shù)據(jù)都是對像,每個對像都有自己的一個類型。不同類型有不同的操作方法,使用內(nèi)置數(shù)據(jù)類型獨有的操作方法,可以更快的完成很多工作2014-02-02
python中閉包Closure函數(shù)作為返回值的方法示例
閉包(closure)是函數(shù)式編程的重要的語法結(jié)構(gòu),Python也支持這一特性,下面這篇文章主要給大家介紹了關(guān)于python中閉包Closure函數(shù)作為返回值的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下。2017-12-12
優(yōu)化Python代碼使其加快作用域內(nèi)的查找
這篇文章主要介紹了優(yōu)化Python代碼使其加快作用域內(nèi)的搜索,文中介紹了CPython相關(guān)的C代碼來對查找功能進行優(yōu)化,加快搜索的速度,需要的朋友可以參考下2015-03-03

