转换后从flash播放器中抓取mp3文件

2024-04-20 08:58:00 发布

您现在位置:Python中文网/ 问答频道 /正文

页面上有一个textarea和一个按钮Synthesize。 如下所示:

        <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代码将如下所示更改(它将创建音频播放器)。在

^{pr2}$

我想从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())

成功的关键是获得mp3文件的URL。 我不知道如何等待脚本更改HTML(即<div id="audioplayer">的内部文本)。 我的代码返回None,因为它更快地获得结果。在


Tags: fromimportdivbrowseridsourcebyselenium
1条回答
网友
1楼 · 发布于 2024-04-20 08:58:00

在发生更改的情况下,仅等待元素是不够的:

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

但您需要使用ExpectedCondition等待它更改某个条件。这是为了让你开始(不是测试):

^{pr2}$

您也可以在此处签出所有预期条件: http://selenium-python.readthedocs.org/en/latest/api.html?highlight=text_to_be_present_in_element#module-selenium.webdriver.support.expected_conditions

相关问题 更多 >