Selenium中readonly文本框通过XPath上传文件,sendKeys无效如何解决?
Ah, I've run into this exact issue before! The readonly text input you're targeting is just a visual placeholder — it doesn't handle the actual file upload logic. Under the hood, there's almost always a hidden <input type="file"> element that's responsible for handling file selections. Here's how to fix this:
Why Your Current Code Isn't Working
The <input type="text" readonly> element is designed only to display the selected filename, not accept file input directly. Even if you remove the readonly attribute, sending a file path to a text input won't trigger the browser's file upload mechanism.
Step-by-Step Fix
1. Locate the Hidden File Input
First, use your browser's developer tools (F12) to inspect the page structure. Look for an <input type="file"> element associated with the "Upload Emote" placeholder. It's probably hidden (via display: none or visibility: hidden) and nested in the same parent container as the readonly text input.
For example, if the structure looks like this:
<div class="upload-container"> <input class="form-field" placeholder="Upload Emote" readonly="" type="text"> <input type="file" style="display: none;" name="emote-file"> </div>
You can locate the file input with this XPath:
WebElement fileInput = adminDriver.findElement(By.xpath("//input[@placeholder='Upload Emote']/../input[@type='file']"));
2. Make the File Input Accessible (If Needed)
Selenium can interact with hidden file inputs directly in most cases, but if you run into issues, use JavaScript to make it visible:
JavascriptExecutor js = (JavascriptExecutor) adminDriver; js.executeScript("arguments[0].style.display = 'block';", fileInput);
3. Send the File Path to the File Input
Now you can use sendKeys() on the file input element — this works because browsers allow file input elements to accept paths via sendKeys regardless of their visibility:
fileInput.sendKeys("/home/smart/Downloads/EMO/(Heart).png");
4. Trigger the Upload (If Required)
Some pages require clicking an upload button after selecting the file. Locate and click that button if needed:
WebElement uploadButton = adminDriver.findElement(By.xpath("//button[contains(text(), 'Upload')]")); uploadButton.click();
Alternative: Directly Set the File Path via JavaScript
If you don't want to modify the element's visibility, you can set the file path directly using JavaScript:
JavascriptExecutor js = (JavascriptExecutor) adminDriver; js.executeScript("arguments[0].value = '/home/smart/Downloads/EMO/(Heart).png';", fileInput); // Don't forget to trigger upload if needed
Key Notes
- Always verify the file input's locator with your browser's dev tools — sometimes the element might be inside an iframe, so you'll need to switch to the iframe first.
- Avoid trying to interact with system file picker windows (Selenium can't control these) — using the file input's
sendKeysis the reliable way to upload files.
内容的提问来源于stack exchange,提问作者Anjali Singh

