To select text as a user would, send one uninterrupted pointer sequence: move to the first character, press and hold the left mouse button, move to the last character, release, and call perform(). Selenium’s mouse model is deliberately small—press, release and move—so selecting a precise range depends on choosing element-relative offsets, scrolling the targets into view and verifying the browser’s resulting selection.
The basic mouse-drag model
A text selection is not a special WebDriver command. It is the browser’s normal hit-testing and selection behavior driven by WebDriver pointer actions. Selenium describes three mouse operations: pressing a button, releasing a pressed button and moving the pointer. A drag selection combines those operations in this order:
- Move to the intended start point.
- Press and hold the left button.
- Move to the intended end point without releasing.
- Release the button.
- Execute the complete action chain.
Moving to an element without offsets normally targets its in-view center. That is convenient for clicking a control, but the center of a paragraph rarely coincides with the first or last character you want. Use offsets relative to the element’s center when the range begins or ends inside the element.
Prepare the page and choose reliable endpoints
Use stable text containers
Locate a paragraph, article body, table cell or other rendered text container with a stable selector. If the range crosses several nodes, use a container that includes both endpoints, or identify separate start and end elements. Avoid selectors tied to generated class names or transient DOM positions.
#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)
Scroll before moving
Pointer coordinates are interpreted in the viewport. Scroll the start and end into view before creating the chain, and wait until layout-affecting content has settled. Lazy images, web fonts, responsive wrapping and animations can move character boundaries after you calculate offsets.
WebElement text = driver.findElement(By.cssSelector(".article-body"));
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollIntoView({block: 'center', inline: 'nearest'});", text);
For a range that starts and ends in different elements, scroll the first element into view, then confirm that both endpoints are visible in the final layout. Scrolling during a held-button drag can change the hit target and produce a different selection.
Measure rendered geometry when precision matters
Offsets are based on rendered pixels, not character indexes. A fixed offset only remains meaningful while the viewport size, device scale, zoom, font metrics and line wrapping remain the same. Set a deterministic window size and browser zoom for repeatable tests. For difficult layouts, inspect getBoundingClientRect() and use a small calibration move rather than assuming the element’s center is a character boundary.
Java: complete Action API example
This example drags from an offset inside a start element to an offset inside an end element. The offsets are relative to each element’s in-view center, which is where moveToElement places the pointer before applying the offset.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesimport java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement start = wait.until(ExpectedConditions.visibilityOfElementLocated(
By.cssSelector(".text-start")));
WebElement end = wait.until(ExpectedConditions.visibilityOfElementLocated(
By.cssSelector(".text-end")));
((JavascriptExecutor) driver).executeScript(
"arguments[0].scrollIntoView({block: 'center', inline: 'nearest'});", start);
int startXOffset = -35; // tune against the rendered start character
int startYOffset = 4;
int endXOffset = 28; // tune against the rendered end character
int endYOffset = 4;
new Actions(driver)
.moveToElement(start, startXOffset, startYOffset)
.clickAndHold()
.moveToElement(end, endXOffset, endYOffset)
.release()
.perform();
The same chain can start and finish in one element:
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
WebElement text = driver.findElement(By.cssSelector(".text"));
new Actions(driver)
.moveToElement(text, -80, -6)
.clickAndHold()
.moveToElement(text, 95, 8)
.release()
.perform();
Why one chain matters
clickAndHold() leaves the button depressed in the action sequence. Calling perform() only after the release keeps the gesture contiguous. Separate commands, an accidental click, or an assertion that runs before release can clear or alter the selection.
Python: ActionChains implementation
Python exposes the same operations through ActionChains. move_to_element_with_offset applies offsets relative to the element’s center; drag_and_drop_by_offset is useful when the endpoint is expressed as a displacement from the current pointer position, but the explicit sequence is easier to reason about for text.
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
wait = WebDriverWait(driver, 10)
start = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".text-start")))
end = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".text-end")))
driver.execute_script(
"arguments[0].scrollIntoView({block: 'center', inline: 'nearest'});",
start,
)
(
ActionChains(driver)
.move_to_element_with_offset(start, -35, 4)
.click_and_hold()
.move_to_element_with_offset(end, 28, 4)
.release()
.perform()
)
For a single element:
ActionChains(driver).move_to_element_with_offset(text, -80, -6)
.click_and_hold()
.move_to_element_with_offset(text, 95, 8)
.release()
.perform()
Verify what the browser selected
A successful pointer gesture does not prove that the intended characters were selected. Read the browser’s current selection and assert it against the expected string. Selection APIs are page state, so verification should happen after the release and may need whitespace normalization when the selection spans line breaks.
String selected = (String) ((JavascriptExecutor) driver).executeScript(
"return window.getSelection ? window.getSelection().toString() : '';"
);
String normalized = selected.replaceAll("\s+", " ").trim();
if (!normalized.equals("Expected text")) {
throw new AssertionError("Selected: " + selected);
}
selected = driver.execute_script(
"return window.getSelection ? window.getSelection().toString() : '';"
)
assert " ".join(selected.split()) == "Expected text"
If the page uses an editor such as a canvas, a shadow DOM component or a custom selection model, window.getSelection() may not expose the application’s value. Assert through that component’s documented state instead.
Offsets, coordinates and responsive layouts
Center versus offset
| Technique | Precision | Best use | Main risk |
|---|---|---|---|
moveToElement(element) |
Low for text | Whole-element interactions | Center may select a middle word or a different line |
moveToElement(element, x, y) / move_to_element_with_offset |
Higher | Known rendered start and end points | Offsets change when layout, zoom or fonts change |
| JavaScript Range | DOM-precise | Testing selection state independent of pointer realism | Does not test the user’s mouse path or hit-testing |
Account for line wrapping
An x-coordinate that selects the desired character on a wide desktop window can land on another line at a narrow width. Run the test at the viewport sizes you support, or calculate a point from the specific text node and line box. Do not reuse desktop offsets for mobile breakpoints.
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)
Handle nested inline elements
Bold spans, links and embedded icons divide text into separate boxes. A drag that crosses them can still work, but the browser may include or exclude boundary whitespace differently. Use endpoint elements close to the actual characters and assert the resulting string rather than relying on element order.
Transforms, zoom and high-DPI displays
CSS transforms alter visual hit-testing, and browser zoom changes the relationship between CSS pixels and device pixels. Keep these settings fixed in CI. If the page itself applies transforms, prefer an endpoint inside the transformed element and tune offsets using its final rendered position.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
When a drag moves the pointer but selects nothing
The pointer starts in the wrong place
Symptom: A selection exists, but it starts several words away. Fix: Replace center-based movement with element-relative offsets. Inspect the element’s rectangle and adjust x and y independently; the y offset must land on the intended line.
The target is outside the viewport
Symptom: Movement throws a WebDriver error or ends at an unexpected location. Fix: scroll the target into view, wait for visibility, and avoid scrolling while the button is held.
A page overlay intercepts the pointer
Symptom: The drag clicks a cookie dialog, tooltip or chat widget. Fix: close the overlay, wait for it to become invisible and then start the chain. An element can be technically present while another layer receives the hit.
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
Layout changes during the gesture
Symptom: The test is intermittent after images, fonts or advertisements load. Fix: wait for the relevant content and network-driven layout to settle, disable animation in the test environment where possible, and use a deterministic viewport.
The Tool Desk
Outbyte Driver Updater FREEFix the driver behind crashes, sound loss and screen glitchesFind Drivers →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →The button remains pressed after an interruption
Symptom: The next interaction behaves like a drag. Fix: issue a release through the binding if possible, reset or clear input state, and start a fresh action sequence. Always put cleanup in the test’s failure-handling path.
Selection is cleared by application JavaScript
Symptom: The browser briefly highlights text, then the highlight disappears. Fix: inspect focus and pointer event handlers. Rich editors may replace native selection with their own model; assert that model or use a DOM Range only when pointer realism is not the test objective.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Native drag versus a JavaScript Range
Use Actions or ActionChains when the requirement is “a user can select this with a mouse.” It exercises pointer movement, button state, hit-testing and the page’s event handlers. It is consequently sensitive to viewport, wrapping, overlays and browser differences.
A JavaScript Range is better when the requirement is only that a DOM text range becomes selected. It can identify text nodes and character offsets deterministically, but it bypasses the physical mouse path and will not reveal pointer-event bugs. Keep the two tests separate so a deterministic state test is not mistaken for an end-to-end gesture test.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallBest 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.
A repeatable test checklist
- Use stable selectors for the start and end containers.
- Fix viewport size, zoom and relevant device settings.
- Scroll the endpoints into view and wait for layout stability.
- Choose offsets based on rendered character positions, not DOM indexes alone.
- Build move, press, move and release as one chain.
- Call
perform()after the release. - Read and assert the resulting selection.
- Release or reset input state after any interrupted gesture.
- Run representative responsive layouts when wrapping changes the range.
Or skip the browser setup
If your goal is a screenshot of the page rather than a test of human text selection, ScreenshotNeo returns an image or PDF through one request. Its capture pipeline accepts cookie and consent banners before the shot and removes more than 60 known consent platforms, newsletter popups and chat widgets; each step can be turned off. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies the page verdict and billing status in headers.
For a direct capture, see the complete option list in the ScreenshotNeo documentation:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo also provides an MCP server with take_screenshot, get_page_info and capture_pdf for Claude, Cursor and other MCP clients. Every feature is included on every plan. The Free plan includes 1,000 shots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account to try it.
Frequently Asked Questions
Can Selenium select text across two different elements?
Yes. Move to an offset in the start element, hold the button, move to an offset in the end element, release, and verify the resulting selection string. The elements must be simultaneously reachable in the final viewport.
Why does the selected string contain unexpected newlines?
Native selection preserves rendered line boundaries. Normalize whitespace for an assertion only when those line breaks are not meaningful to the behavior under test.
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.

