You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python Selenium中如何用execute_script模拟回车键?send_keys/submit失效

Fixing Enter Key Simulation After JavaScript Input in Selenium

Got it, let's work through this problem! You've successfully injected text into the textarea using JavaScript, but send_keys(Keys.ENTER) and submit() aren't cutting it for sending the content. Here are some practical workarounds tailored to this scenario:

1. Simulate Enter Key via JavaScript Keyboard Events

Since direct Selenium keyboard methods aren't working, we can use JavaScript to dispatch a proper Enter key event to the textarea. This often works because it bypasses any focus issues or custom event handlers that might block Selenium's send_keys.

First, make sure to trigger an input event first (some apps rely on this to detect content changes), then dispatch the Enter keydown event:

f = driver.find_element_by_css_selector("textarea._bilrf")

# Set the value and trigger input event
driver.execute_script("""
    arguments[0].value = 'Hi!';
    arguments[0].dispatchEvent(new Event('input', { bubbles: true }));
""", f)

# Simulate pressing Enter
driver.execute_script("""
    const enterEvent = new KeyboardEvent('keydown', {
        key: 'Enter',
        code: 'Enter',
        keyCode: 13,
        bubbles: true,
        cancelable: true
    });
    arguments[0].dispatchEvent(enterEvent);
""", f)

If that doesn't work, you can try adding keyup and keypress events too (some apps listen for all three):

driver.execute_script("""
    const element = arguments[0];
    // Trigger input event
    element.dispatchEvent(new Event('input', { bubbles: true }));
    // Dispatch full key sequence
    ['keydown', 'keypress', 'keyup'].forEach(eventType => {
        element.dispatchEvent(new KeyboardEvent(eventType, {
            key: 'Enter',
            code: 'Enter',
            keyCode: 13,
            which: 13,
            bubbles: true,
            cancelable: true
        }));
    });
""", f)

2. Locate and Click the Send Button

If the page has a visible (or even hidden) send button, this is often the most reliable approach. Apps frequently tie send actions to button clicks instead of Enter keys, so bypassing the keyboard entirely might work:

# Replace with the actual CSS selector for your send button
send_button = driver.find_element_by_css_selector("button[aria-label='Send'], .send-button")
send_button.click()

Pro tip: Use your browser's dev tools to inspect the send button and find a unique selector (like an id, aria-label, or specific class).

3. Submit the Parent Form (If Applicable)

If the textarea is wrapped inside a <form> element, you can trigger the form's submit action directly via JavaScript:

f = driver.find_element_by_css_selector("textarea._bilrf")
# Find the parent form element
form = f.find_element_by_xpath("./ancestor::form")
# Submit the form
driver.execute_script("arguments[0].submit();", form)

Why send_keys and submit Might Be Failing

  • send_keys(Keys.ENTER): The textarea might not have focus when you call this, or the app uses custom event listeners that don't respond to Selenium's simulated key presses. Also, directly setting the value with JS doesn't automatically give the element focus.
  • submit(): This method only works on <form> elements. If your textarea isn't inside a form, or the app doesn't use form submission for sending messages, this method will do nothing.
  • Missing Event Triggers: When you set the value via JS, you skip the natural user events (like typing) that the app expects. Many apps listen for input or change events to enable the send button or process the text—without triggering these, the app might not recognize that the textarea has content.

内容的提问来源于stack exchange,提问作者Hamed Baziyad

火山引擎 最新活动