【问题标题】:Python Selenium - Send_keys() execution speed too slow when inputting large stringsPython Selenium - 输入大字符串时 Send_keys() 执行速度太慢
【发布时间】:2023-02-17 13:38:53
【问题描述】:

我们正在努力将大量字符串放入输入框中。

使用 Send_keys() 时,工作时间过长。

这是我找到的解决此问题的方法。

import pyperclip
from selenium.webdriver.common.keys import Keys
pyperclip.copy('foo')
element.send_keys(Keys.CONTROL, 'v')

这非常有效,但在无头模式下返回空值。

有没有办法在 Heldless 模式下解决这个问题?

【问题讨论】:

    标签: python selenium clipboard headless-browser


    【解决方案1】:

    我看到 Stackoverflow 上已经有几个关于这个问题的问题。
    首先-请尝试this 建议使用klembord而不是pyperclip的解决方案:

    from selenium import webdriver
    from selenium.webdriver.firefox.options import Options
    from webdriver_manager.firefox import GeckoDriverManager
    import klembord
    klembord.init()
    options = Options()
    options.headless = True
    driver = webdriver.Firefox(options=options,executable_path=GeckoDriverManager().install())
    print("Headless Firefox Initialized. Wait for output")
    driver.get("https://www.lipsum.com")
    l = driver.find_element_by_xpath("/html/body/div/div[2]/div[2]/div[3]/div[1]/p")
    klembord.set_text(l.text) # setting text to clipboard
    print("Check clipboard by pressing WIN + V or CTRL +V")
    driver.quit()
    

    另一种克服问题的尝试,但在 Java 中 is here:

    【讨论】:

      【解决方案2】:

      不确定您使用的是哪个浏览器或操作系统平台,但通常操作系统不允许无头浏览器访问/许可操作系统剪贴板,或者浏览器没有在无头模式下设置复制功能。

      由于您已经确定了 WebElement,因此您应该尝试使用 Javascript 方法,因此在您的情况下:

      driver.execute_script('element.value="TestText";')

      或者

      driver.execute_script('element').setAttribute('value','TestText');

      实际上,Javascript 方法将您的内容(在上面的“Testtest”示例中)传递到您使用 .value 函数定义的元素中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-22
        • 1970-01-01
        • 1970-01-01
        • 2016-05-29
        • 2017-08-11
        • 1970-01-01
        相关资源
        最近更新 更多