使用 Selenium (PYTHON) 获取文本时出现问题

问题描述 投票:0回答:1

我正在尝试使用 Selenium 为我的 AI 语音助手构建语音到文本,到目前为止,除了我无法获取输出文本之外,一切都很顺利。 这是我正在使用的用于语音转文本的网站。 这是我的代码:

from time import sleep import warnings from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.chrome.service import Service warnings.simplefilter("ignore") try: path = "c:\\Users\\Utente\\Desktop\\SPARK\\chromedriver.exe" options = webdriver.ChromeOptions() options.headless = False options.add_experimental_option("excludeSwitches", ["enable-logging"]) options.add_argument("--log-level=3") service = Service(path) options.add_argument("--use-fake-ui-for-media-stream") options.add_argument("--use-fake-device-for-media-stream") driver = webdriver.Chrome(options=options) driver.get("https://speechnotes.co/dictate/") sleep(1.5) it_button_xpath = "/html/body/div[4]/div/div[1]/div[1]/div[2]/select/option[42]" driver.find_element(by=By.XPATH, value=it_button_xpath).click() sleep(0.1) start_button_xpath = "/html/body/div[4]/div/div[1]/div[1]/div[2]/div" driver.find_element(by=By.XPATH, value=start_button_xpath).click() print("Listening...") except Exception as e: print(e) while True: text_element_xpath = "/html/body/div[4]/div/div[1]/div[2]" text = driver.find_element(by=By.XPATH, value=text_element_xpath).text text = text.strip() stop = input("Type anything to stop --> ") print(text) if stop != "": driver.quit() break
我很确定这是因为我得到了错误的输出框元素的 xpath,但我尝试了所有我能想到的方法,但它仍然不起作用。
另外,如果它有任何帮助,当我尝试 print(len(text)) 时它给出 3,我不知道为什么。
请大家帮忙,
谢谢

我尝试了

start_button_xpath = "/html/body/div[4]/div/div[1]/div[1]/div[2]/div"

以及
start_button_xpath = "/html/body/div[4]/div/div[1]/div[1]/div[2]/div/textarea"
,但它不起作用(没有打印任何内容)。

python selenium-webdriver speech-to-text
1个回答
0
投票
您的代码中有几个问题。

    不要使用绝对 xpath 定位器。您的元素上有非常独特的定位器,id
  1. start_button
    copy_button
  2. 口述文本后,DOM 中没有直接元素包含它。但是,您有
  3. copyButton
     可以复制剪贴板中的文本。你只需要得到它。例如,使用 
    pyperclip
请注意,Google Ads 模式可能会拦截对复制按钮的点击。因此,如果您有它 - 您需要将其设为不可见或将其关闭。

import pyperclip from selenium.webdriver.common.by import By from selenium import webdriver # previous code driver.find_element(By.ID, 'start_button').click() print("Listening...") while True: stop = input("Type anything to stop --> ") if stop != "": copy = driver.find_element(By.ID, 'copyButton') copy.click() copied_text = pyperclip.paste() print(copied_text) driver.quit() break
    
© www.soinside.com 2019 - 2024. All rights reserved.