The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →To select a text range with Selenium, perform one uninterrupted pointer gesture: move to the start point, press and hold the left mouse button, move to the end point, release it, and execute the action sequence. Element centers are only defaults; use offsets when the desired character starts or ends inside an element. Scroll the text into view first, then verify the browser’s actual selection rather than assuming that a completed drag selected the intended words.
How Selenium represents a text-selection drag
WebDriver does not have a special “select text” command. Its mouse model consists of pointer movement, button press, and button release. A selection gesture therefore has four practical stages:
- Move the pointer to the rendered start position.
- Press and hold the primary (left) button.
- Move to the rendered end position while holding the button.
- Release the button and call
perform().
The browser, not Selenium, decides which text characters lie under those coordinates. Rich text, nested inline elements, responsive wrapping, transforms, zoom, and custom selection handlers can all affect the result.
Reliable procedure
1. Find a stable text container
Locate a container that remains present after the page finishes rendering. If the start and end are in different elements, locate both endpoints. Avoid brittle selectors tied to generated class names.
#1 Best Overall
- Compact Mouse: With a comfortable and contoured shape, this Logitech ambidextrous wireless mouse feels great in either right or left hand and is far superior to a touchpad
- Durable and Reliable: This USB wireless mouse features a line-by-line scroll wheel, up to 1 year of battery life (2) thanks to a smart sleep mode function, and comes with the included AA battery
- Universal Compatibility: Your Logitech mouse works with your Windows PC, Mac, or laptop, so no matter what type of computer you own today or buy tomorrow your mouse will be compatible
- Plug and Play Simplicity: Just plug in the tiny nano USB receiver and start working in seconds with a strong, reliable connection to your wireless computer mouse up to 33 feet / 10 m (5)
- Better than touchpad: Get more done by adding M185 to your laptop; according to a recent study, laptop users who chose this mouse over a touchpad were 50% more productive (3) and worked 30% faster (4)
2. Bring the target into the viewport
Pointer coordinates are viewport-based. Scroll the container into view before building the chain, and wait until layout-affecting content such as fonts or images has settled.
3. Convert the desired characters to coordinates
moveToElement and its Python equivalent target an element’s in-view center by default. That is rarely the exact character boundary you want. Element-relative offsets let you begin and end at points inside the element. Offsets are relative to the element’s in-view center, not its top-left corner, so calculate them from the element’s current rectangle.
4. Use one uninterrupted chain
Do not release between the start and end moves. Construct the complete sequence, then execute it once with perform().
5. Assert the resulting selection
Read the browser selection after the gesture and compare it with the expected string. This catches off-by-one characters and layout changes that a successful pointer action alone cannot reveal.
Free tools Windows power users keep installed
One-click scans. No signup required.
Java: select text with Actions
This example selects from an offset in one text element to an offset in another. Replace the selectors and offsets with coordinates appropriate to your rendered page.
Rank #2
- The next-generation optical HERO sensor delivers incredible performance and up to 10x the power efficiency over previous generations, with 400 IPS precision and up to 12,000 DPI sensitivity
- Ultra-fast LIGHTSPEED wireless technology gives you a lag-free gaming experience, delivering incredible responsiveness and reliability with 1 ms report rate for competition-level performance
- G305 wireless mouse boasts an incredible 250 hours of continuous gameplay on just 1 AA battery; switch to Endurance mode via Logitech G HUB software and extend battery life up to 9 months
- Wireless does not have to mean heavy, G305 lightweight mouse provides high maneuverability coming in at only 3.4 oz thanks to efficient lightweight mechanical design and ultra-efficient battery usage
- The durable, compact design with built-in nano receiver storage makes G305 not just a great portable desktop mouse, but also a great laptop travel companion, use with a gaming laptop and play anywhere
import java.time.Duration;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
class TextSelectionTest {
@Test
void selectsExpectedRange() {
WebDriver driver = new ChromeDriver();
try {
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(2));
driver.get("https://example.test/article");
WebElement start = driver.findElement(By.cssSelector(".article-text"));
WebElement end = driver.findElement(By.cssSelector(".article-text-end"));
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollIntoView({block:'center', inline:'nearest'});", start);
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollIntoView({block:'center', inline:'nearest'});", end);
new Actions(driver)
.moveToElement(start, 18, -6)
.clickAndHold()
.moveToElement(end, -12, 8)
.release()
.perform();
String selected = (String) ((JavascriptExecutor) driver).executeScript(
"return window.getSelection ? window.getSelection().toString() : '';"
);
Assertions.assertEquals("expected text", selected);
} finally {
driver.quit();
}
}
}
clickAndHold() presses without releasing. The following moveToElement runs while the button is down, and release() completes the selection. Calling perform() is essential; without it, the chain is only a description of actions.
When both endpoints are in one element
Use the same element for both moves, with different offsets:
new Actions(driver)
.moveToElement(text, startXOffset, startYOffset)
.clickAndHold()
.moveToElement(text, endXOffset, endYOffset)
.release()
.perform();
Offsets can be positive or negative. Because they are center-relative, inspect the element’s width and height with JavaScript or your browser’s developer tools when choosing them.
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchPC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Python: the equivalent ActionChains gesture
Python exposes the same pointer sequence through ActionChains. This runnable test uses element-relative offsets and verifies the result with page JavaScript.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
try:
driver.get("https://example.test/article")
wait = WebDriverWait(driver, 15)
text = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".article-text")))
end = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".article-text-end")))
driver.execute_script(
"arguments[0].scrollIntoView({block:'center', inline:'nearest'});", text)
driver.execute_script(
"arguments[0].scrollIntoView({block:'center', inline:'nearest'});", end)
(ActionChains(driver)
.move_to_element_with_offset(text, 18, -6)
.click_and_hold()
.move_to_element_with_offset(end, -12, 8)
.release()
.perform())
selected = driver.execute_script(
"return window.getSelection ? window.getSelection().toString() : '';"
)
assert selected == "expected text", repr(selected)
finally:
driver.quit()
Python also provides drag_and_drop_by_offset for an offset drag. The explicit move/hold/move/release form is usually clearer for text because it makes both endpoints and the button state visible in the test.
Rank #3
- Compact Mouse: With a comfortable and contoured shape, this Logitech ambidextrous wireless mouse feels great in either right or left hand and is far superior to a touchpad
- Durable and Reliable: This USB wireless mouse features a line-by-line scroll wheel, up to 1 year of battery life (2) thanks to a smart sleep mode function, and comes with the included AA battery
- Universal Compatibility: Your Logitech mouse works with your Windows PC, Mac, or laptop, so no matter what type of computer you own today or buy tomorrow your mouse will be compatible
- Plug and Play Simplicity: Just plug in the tiny nano USB receiver and start working in seconds with a strong, reliable connection to your wireless computer mouse up to 33 feet / 10 m (5)
- Better than touchpad: Get more done by adding M185 to your laptop; according to a recent study, laptop users who chose this mouse over a touchpad were 50% more productive (3) and worked 30% faster (4)
Choosing offsets that land on characters
An offset is a physical point, not a character index. The same offset can map to different characters when the viewport, font, device-pixel ratio, line wrapping, or browser zoom changes.
- Fix the test viewport and browser zoom when pixel-sensitive selection is unavoidable.
- Wait for web fonts and asynchronous content before calculating positions.
- Keep the pointer inside the text element at both endpoints.
- For multi-line text, select within a stable line or use an endpoint element positioned at the intended line.
- Test at the responsive breakpoints your product supports; wrapping changes character coordinates.
If the page contains nested links, spans, icons, or inline controls, the visible text may be split across several boxes. In that case, use separate start and end elements or a small endpoint marker in the test fixture rather than assuming one container’s center describes the whole range.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Verifying and debugging the selection
Read the selection with JavaScript
The browser Selection API provides a practical assertion:
return window.getSelection ? window.getSelection().toString() : '';
An empty string can mean that the drag missed text, the page cleared the selection, the document is inside an iframe, or the application uses a custom selection implementation.
Capture useful diagnostics
- Save a screenshot immediately after the drag.
- Log the start and end element rectangles, viewport dimensions, device-pixel ratio, and chosen offsets.
- Log the returned selection string, including its length and escaped whitespace.
- Record the active element and whether the target is inside an iframe or shadow root.
Iframe and shadow-root boundaries
Switch into the correct iframe before locating or interacting with its text. Shadow DOM content may require obtaining the shadow root and locating elements within it. A pointer can visually cross boundaries, but WebDriver element lookups still follow document ownership rules.
Rank #4
- Computer mouse for easily navigating a computer interface; click, scroll, and more
- USB-A wired connection; if existing device only supports USB-C, an additional adapter will be required
- High-definition (1000 dpi) optical tracking ensures responsive cursor control for precise tracking and easy text selection
- 3 buttons offer effortless fingertip control
- Plug-and-go ready for instant use
Common failures and fixes
The pointer moves, but no text is selected
Cause: The start or end landed on whitespace, a non-text child, or an overlay. Fix: scroll first, wait for overlays to disappear, and replace center coordinates with measured offsets. Verify with window.getSelection().toString().
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteThe wrong characters are highlighted
Cause: Element centers are being used as character boundaries, or the layout wrapped differently. Fix: use element-relative offsets, stabilize the viewport and fonts, and assert the exact string.
moveToElement reports an interaction or out-of-bounds error
Cause: The element is not currently in the viewport, is obscured, or has changed position between locating and moving. Fix: re-locate after dynamic updates, call scrollIntoView, wait for visibility, and check for fixed headers or modal layers.
The drag selects only part of a line
Cause: The endpoint was calculated against an old width or line wrap. Fix: calculate after layout settles and use a line-specific endpoint. Avoid hard-coded offsets across substantially different viewport sizes.
A later test behaves as if the mouse button is still down
Cause: An exception interrupted the chain after the press. Fix: release or reset the input state using the methods available in your Selenium binding, then start a fresh action sequence. Put cleanup in a test teardown so one failure cannot contaminate the next test.
Best Value
- 【Plug and Play for Home/Office/School】The wireless computer mouse features 2.4GHz connectivity, delivering a stable, interference-free connection up to 32ft. Designed for 𝐦𝐞𝐝𝐢𝐮𝐦 𝐭𝐨 𝐥𝐚𝐫𝐠𝐞 𝐬𝐢𝐳𝐞𝐝 𝐡𝐚𝐧𝐝𝐬, it ensures comfortable use all day. Simply plug in the USB-A receiver for instant pairing—no drivers needed. 📌📌 If the mouse isn’t suitable, place the USB receiver in the battery compartment and return both.
- 【3 Levels Adjustable DPI】This travel USB mouse offers 3 adjustable DPI settings (800, 1200, 1600), allowing you to customize sensitivity for precise design work. Effortlessly switch to match your task and elevate your productivity. 📌 Please remove the film at the bottom of the mouse before use.
- 【Effortless Browsing】Equipped with forward and backward buttons, this computer mice streamlines your workflow, making it easy to navigate through web pages and files with a simple click. 📌Side button does not work on Mac.
- 【Visible Indicator Light】 The pc mouse features a visual indicator for DPI levels and low battery alerts. The red light flashes once for 800 DPI, twice for 1200 DPI, and three times for 1600 DPI. When the battery level is below 10%, the light flashes red until the mouse is completely out of power.
- 【Click to Wake】With smart sleep mode, it saves power by standby after 10 inactive minutes, just 2-3 clicks to wake. This efficient design delivers 3x longer battery life than motion-wake mice. Engineered for durability, its buttons and scroll wheel are tested for 10 million clicks, ensuring long-term reliability and consistent performance.
The expected text differs only by whitespace
Cause: Browser selection preserves line breaks and spacing according to rendered layout. Fix: decide whether whitespace is part of the contract; if not, normalize it explicitly in the assertion while retaining a separate exact-selection test where whitespace matters.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Mouse drag versus JavaScript range selection
| Approach | What it tests | Precision | Main trade-off |
|---|---|---|---|
| Actions/ActionChains drag | A user-like pointer gesture and the page’s real hit testing | Coordinate-dependent; offsets improve control | Sensitive to layout, viewport, fonts, overlays, and responsive wrapping |
| JavaScript Range/Selection APIs | DOM selection state | Can target text nodes and offsets directly | Does not simulate the user’s mouse path or expose pointer-interaction bugs |
Use a drag when the requirement is “a user can select this with the mouse,” including pages that respond to pointer events. Use a DOM range when the requirement is deterministic selection state and pointer fidelity is irrelevant. Many suites use both: a small number of end-to-end drag tests plus faster range-based checks for application logic.
Making drag-selection tests stable
- Use explicit waits for visibility and any application-specific “rendered” condition.
- Keep browser dimensions, zoom, and device scale consistent in CI.
- Prefer test fixtures with predictable typography and endpoint markers.
- Do not chain a drag immediately after an animation, resize, or lazy-load event.
- Assert the selected value and retain a screenshot on failure.
- Keep the gesture short and direct; unnecessary intermediate moves add more opportunities for hit-testing differences.
Or skip the browser setup
If your goal is a page image rather than testing a human selection gesture, ScreenshotNeo returns a screenshot or PDF from one request. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers.
cURL:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python:
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
open("shot.webp", "wb").write(r.content)
Node.js:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
const image = Buffer.from(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', image));
See the ScreenshotNeo documentation for request options. It also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients. Features include full-page and element capture, device presets, custom CSS and JavaScript, waits, request blocking, cookies and headers, geolocation, resizing, caching, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, and a usage API. The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
Frequently Asked Questions
Can Selenium select text by character index alone?
Not with a mouse action. A drag uses rendered viewport coordinates, so character positions must be translated to element-relative points or selected through a separate DOM Range approach.
Should I use drag_and_drop for text?
Use the explicit move, click-and-hold, move, and release sequence when you need clear control of both text endpoints. Offset drag helpers are useful, but they do not remove the need to verify the resulting selection.
How do I select text from right to left?
Reverse the start and end coordinates in the same gesture. Assert the browser’s returned selection because direction and whitespace behavior can vary with the page layout.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Recommended Free Tools

