2015-04-27 25 views
0

在頁面上有一個textarea和一個按鈕Synthesize。 它看起來如下:轉換後從Flash播放器中抓取mp3文件

 <textarea id="ttstext" name="text" style="font-size: 130%; width: 100%; 
     height: 120px; padding: 5px;"></textarea> 
     ... 
     <div id="audioplayer"> 
      <script> 
       create_playback(); 
      </script><audio autoplay="" autobuffer="" controls=""></audio> 
     </div> 
     <input id="commitbtn" value="Synthesize" type="submit"> 

當我點擊按鈕synthesize,網頁的HTML代碼將發生如下變化(這將創建音頻播放器)。

<div id="audioplayer" style="display: block;"><embed width="370" height="20" flashvars="height=20&amp;width=370&amp;type=mp3&amp;file=http://services.abc.xyz.mp3&amp;showstop=true&amp;usefullscreen=false&amp;autostart=true" allowfullscreen="true" allowscriptaccess="always" quality="high" name="mpl" id="mpl" style="undefined" src="/demo/mediaplayer.swf" type="application/x-shockwave-flash"></div> 

我想從Python代碼生成mp3文件。

我到目前爲止試過的東西。

#!/usr/bin/env python 
# encoding: utf-8 
from __future__ import unicode_literals 
from contextlib import closing 
from selenium.webdriver import Firefox 
from selenium.webdriver.support.ui import WebDriverWait 
import BeautifulSoup 
import time 

url = "http://www..." 

def textToSpeech(): 
    with closing(Firefox()) as browser: 
    try: 
     browser.get(url) 
    except selenium.common.exceptions.TimeoutException: 
     print "timeout" 
    browser.find_element_by_id("ttstext").send_keys("Hello.") 
    button = browser.find_element_by_id("commitbtn") 
    button.click() 
    time.sleep(10) 
    WebDriverWait(browser, timeout=100).until(
     lambda x: x.find_element_by_id('audioplayer')) 
    src = browser.page_source 
    return src 

def getAudio(source): 
    soup = BeautifulSoup.BeautifulSoup(source) 
    audio = soup.find("div", {"id": "audioplayer"}) 
    return audio.string 


if __name__ == "__main__": 
    print getAudio(textToSpeech()) 

成功的關鍵是將URL獲取到生成的mp3文件。 我不知道如何等待腳本改變HTML(內部文本<div id="audioplayer">)。 我的代碼返回None,因爲它會更快得到結果。

+0

出現在'div'的URL,因爲'div'顯示出來? – bosnjak

+0

@勞倫斯號碼點擊「合成」按鈕後,將會從textarea生成帶有mp3文件的網址。 – xralf

+0

在創建mp3之後,這可能需要很長時間,對吧? – bosnjak

回答

1

在變化的情況下,這是不夠的等待元素:

WebDriverWait(browser, timeout=100).until(
     lambda x: x.find_element_by_id('audioplayer')) 

但是,你需要等待它的改變在一定條件下,利用ExpectedCondition。這是爲了讓你開始(未測試):

from selenium.webdriver.support import expected_conditions as EC 
wait_text = 'file=http://' 
element = WebDriverWait(driver, 10).until(
     EC.text_to_be_present_in_element((By.ID, "myDynamicElement"), wait_text) 
    ) 

您還可以在這裏購物結帳預期條件: http://selenium-python.readthedocs.org/en/latest/api.html?highlight=text_to_be_present_in_element#module-selenium.webdriver.support.expected_conditions

+0

現在,它等待,但它會以'selenium.common.exceptions.TimeoutException'結束。你確定文字出現在元素中嗎?它實際上是子元素參數的一部分。 – xralf

+0

正如我所說,我不確定,我沒有測試過它。你需要弄清楚你正在等待什麼文本,我沒有一個在這裏運行的例子。 – bosnjak

+0

我不知道'text_to_be_present_in_element'在哪裏搜索wait_text。這沒有奏效。但它幫助我理解了邏輯。我試着用'find_element_by_id('mpl')'來第一次等待,並且它可以工作。 – xralf