如何在Python Selenium中用JavascriptExecutor替代send_keys?
execute_script Issues Hey there! I totally get the frustration of dealing with glacial send_keys speeds for large text content, and it's annoying when your execute_script attempt doesn't update the page even without errors. Let's break down why that happened and fix it properly.
Why Your Original execute_script Didn't Work
When you set the value attribute via setAttribute, you're only updating the DOM property—but many modern web forms rely on JavaScript events (like input or change) to detect content changes and sync them with the page's UI or backend logic. Your code didn't trigger those events, so the page never registered the new text.
Solution 1: Update Value + Trigger Required Events
This approach directly sets the textarea's value and fires the input event (most forms listen for this) to make the page recognize the change. Here's how to adjust your code:
from selenium import webdriver text = "gckugcgaygartty" # Replace with your large text content link_url = "http://www.bioinformatics.org/sms2/translate.html" driver = webdriver.Chrome('chromedriver') # Note: chrome_options is deprecated in newer Selenium versions, use options instead driver.get(link_url) textarea = driver.find_element_by_tag_name("textarea") # Clear the textarea first, then set value and trigger input event driver.execute_script(""" arguments[0].value = ''; arguments[0].value = arguments[1]; arguments[0].dispatchEvent(new Event('input')); """, textarea, text)
If the input event alone doesn't work, you can add the change event too (some forms listen for this when the field loses focus):
driver.execute_script(""" const textarea = arguments[0]; textarea.value = arguments[1]; textarea.dispatchEvent(new Event('input')); textarea.dispatchEvent(new Event('change')); """, textarea, text)
Solution 2: Use System Clipboard for Ultra-Fast Paste
For extremely large text, using the system clipboard to paste is often faster than any DOM manipulation. Here's how to do it:
from selenium import webdriver from selenium.webdriver.common.keys import Keys import pyperclip text = "gckugcgaygartty" link_url = "http://www.bioinformatics.org/sms2/translate.html" driver = webdriver.Chrome('chromedriver') driver.get(link_url) textarea = driver.find_element_by_tag_name("textarea") textarea.clear() # Copy text to clipboard, then paste pyperclip.copy(text) # Use COMMAND instead of CONTROL if you're on Mac textarea.send_keys(Keys.CONTROL, 'v')
Quick Note on Deprecations
Also, heads up: chrome_options is deprecated in newer Selenium versions. If you're using Selenium 4+, you should use options like this:
from selenium.webdriver.chrome.options import Options options = Options() # Add any options you need, e.g., options.add_argument("--headless") driver = webdriver.Chrome(options=options)
内容的提问来源于stack exchange,提问作者Daves

