Discovering a moving element and inputting text using Selenium with C#

UPDATE: I'm not entirely certain if this detail will help, but the platform is Sharepoint-based.

I am encountering difficulty in locating an element with a special character using Webdriver.

var element = wait.Until(x => x.FindElement(By.Id("Tasrit_6aecdca9-e3b9-4141-ae36-d537784f9592_$TextField_inplacerte")));
element.SendKeys("foo");

It appears that the issue may be related to the $ symbol.

However, I managed to identify it by employing :

var element = wait.Until(x => x.FindElements(By.CssSelector("div[id*='Tasrit_6aecdca9-e3b9-4141-ae36-d537784f9592']")));
element[2].FindElement(By.TagName("p")).SendKeys("foo");

The test seems to pass in this manner, but the data doesn't actually get sent to the field. Regrettably, there is no input tag in the element's structure, and upon manual text insertion, it becomes apparent that the value was placed within the <p> tag. However, utilizing the <p> tag as shown does not yield the desired outcome.

The HTML:

<div class="ms-rtestate-write ms-rteflags-0 ms-rtestate-field" id="Tasrit_6aecdca9-e3b9-4141-ae36-d537784f9592_$TextField_inplacerte" role="textbox" aria-haspopup="true" aria-labelledby="Tasrit_6aecdca9-e3b9-4141-ae36-d537784f9592_$TextField_inplacerte_label" style="min-height: 84px;" contenteditable="true" aria-autocomplete="both" aria-multiline="true" RteDirty="true">
  <p>
    <span id="ms-rterangecursor-start" RteNodeId="1"></span>
    <span id="ms-rterangecursor-end"></span>
  ​</p>
</div>

Answer №1

Why implement two FindElement* when you can combine them into a single step:

  • CssSelector:

    wait.Until(x => x.FindElement(By.CssSelector("div.ms-rtestate-write.ms-rteflags-0.ms-rtestate-field[id^='Tasrit_'][aria-labelledby$='_inplacerte_label']>p"))).SendKeys("foo");
    
  • XPath:

    wait.Until(x => x.FindElement(By.XPath("//div[@class='ms-rtestate-write ms-rteflags-0 ms-rtestate-field' and starts-with(@id,'Tasrit_')][contains(@aria-labelledby,'_inplacerte_label')]/p"))).SendKeys("foo");
    

Update

If the element appears dynamic, use WebDriverwait to wait for the element to be clickable. You can try these solutions:

  • CssSelector:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("div.ms-rtestate-write.ms-rteflags-0.ms-rtestate-field[id^='Tasrit_'][aria-labelledby$='_inplacerte_label']>p"))).SendKeys("foo");
    
  • XPath:

    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(ExpectedConditions.ElementToBeClickable(By.XPath("//div[@class='ms-rtestate-write ms-rteflags-0 ms-rtestate-field' and starts-with(@id,'Tasrit_')][contains(@aria-labelledby,'_inplacerte_label')]/p"))).SendKeys("foo");
    

Answer №2

If the function SendKeys() is not functioning properly, one alternative solution could be to utilize JavaScript

IWebElement webElement = element[2].FindElement(By.TagName("p"));
driver.ExecuteJavaScript("arguments[0].setAttribute('value', 'arguments[1]')", webElement, "foo");

Answer №3

Looks like there might be a bit of extra space in the ID of that element :) Give this a try:

wait.Until(x => x.FindElement(By.Id("Tasrit_6aecdca9-e3b9-4141-ae36-d537784f9592_$TextField_inplacerte")));
element.Click();

It's possible that the ID value of the element in the DOM is different, maybe $TextField_inplacerte represents something like spaceMonkey, undefined, 5, etc. You can inspect the element in the dev tools to verify its actual ID in the DOM.

You could use the dev tools API to search for text in the DOM with the element and check if the ID matches or not. There might be a difference in any part of the ID, like the 6th character being different :)

To confirm if the space between the first part of the ID and '24' is causing the issue, you have a couple of options:

  1. Check the webdriver's source code to see how it accesses DOM elements internally

  2. Try loading jQuery before testing this out:

    var element = wait.Until(x => x.FindElements($('#id containing spaces')).SendKeys("foo");

Instead of using the webdriver method to find the element, using jQuery to reference the element may work. If it does, then the issue could be due to spaces in the element's ID caused by poor application design.

This might explain why the CSS selector approach worked.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Execute Selenium Grid - The process of uploading multiple files simultaneously to a webpage by using sendkeys

We are currently utilizing Selenium BDD scenarios on a Selenium Grid with Chrome browsers and Windows operating systems for the node machines. One of our scenarios involves uploading multiple files to a webpage. Here is the code I am using for remote execu ...

Trigger modal following unsuccessful registration

I have a method in the controller for registering users. [HttpPost] public ActionResult Register(RegisterViewModel register) { if (this.IsCaptchaValid("Captcha is not valid")) { if (ModelState.IsValid) { ...

firefox selenium webdriver geckodriver compatibility issue

Encountering an error while attempting to launch Firefox browser in Eclipse. The error message reads as follows: Usage: E:\new gecko\geckodriver.exe [OPTIONS] E:\new gecko\geckodriver.exe: Unknown option --port=30415 Exception ...

A guide on efficiently deserializing the JSON response from an API using C#

Is there a way to create models from the JSON data, particularly if the data includes a string keyword name? The JSON Data: { "Meta Data": { "1. Information": "Intraday (5min) open, high, low, close prices and volume&q ...

Defining Xpath in Selenium: A Complete Guide

When attempting to select the checkbox labeled "In Process," I am using the following xpath: However, upon running the code below, I am encountering a No such Element Exception: String ds = "//*[@id='ctl00_ctl00_Content_MainPlaceHolder_cblStatuses ...

Using Jquery.Ajax to send a pair of arguments to a POST api请求

My controller method has the following structure: [HttpPost] public HttpResponseMessage SaveFunc(ChangeRequest[] changeRequests, string comment) { //perform actions } In this method, a user can save a set of changerequ ...

Exploring the possibilities of utilizing Selenium variables in Python 3 to automate email creation

Hi there! This is my first post and I'm fairly new to Python, especially when it comes to sending emails from it. My current objective is to scrape the first 5 articles from a website and send them to my email address. Right now, all I need is for it ...

Learn how to utilize the foreach loop in C# to iterate through an array and retrieve its

{ "Config": { "controls": [ { "id": 1, "name": "test", "inputs": [ { } ] }, { "id": 2, "name": "xyz", "inputs": [ { } ] } ...

The current_url loop is getting stuck on various unexpected links

My current challenge involves fetching the URL for webpages that redirect to other URLs when clicked. However, my loop seems to get stuck on random pages without any consistency in which page it happens. There are no errors thrown, and it enters an infinit ...

When using Gradle with TestNG, only specific tests are executed individually

I've been using Gradle in combination with TestNG, Java, and Selenium to execute my web UI tests for a considerable period of time. However, I have recently encountered a perplexing issue. When attempting to run a single test class specifying -DtaskNa ...

The setTimeout functionality is executing faster than expected

In my selenium test, I've noticed that the setTimeout function consistently finishes about 25% faster than it should. For example, when waiting for 20 seconds, the function completes after only 15 seconds. test.describe('basic login test',f ...

Having trouble locating and clicking an element using Selenium and Java

On the page, there is a specific button that needs to be clicked: <div _ngcontent-jnk-c107="" class="btn btn-primary btn-outline" tabindex="0" ng-reflect-router-link="/opportunity/1">VIEW</div> Identifyi ...

The amazing capabilities of Jmeter's WebDriver Sampler - Unleashing the Power of CSS Locator Wild

Recently, I've been utilizing Jmeter's built-in WebDriver Sampler with Selenium for web scraping. The Situation: In a particular scenario, it is crucial for me to only select the default date that is automatically chosen when opening a datepicke ...

Selenium ceases to function intermittently

I am attempting to extract data from a website that has a total of 9000 pages. However, the extraction process stops after retrieving approximately 1700 pages and then restarts from the beginning and continues for about 1000 more pages. Is there a way to s ...

Comparing screens through automated testing

Currently utilizing Webdriver in conjunction with C#, one major challenge is that Webdriver cannot test design elements. Therefore, I am exploring the idea of implementing a screenshot comparison tool. Given that I am working on a large website with freque ...

Error: Unable to locate elements due to a null XPath expression. This issue arises while attempting to input keys using a Method

Encountering an error when using Sendkeys in methods. public static void inputTask(String task) throws Exception { // Entering task name GUIFunctions.typeTxtboxValue(driver,By.xpath(ObjRepoProp.getProperty("inputTaskName_XPATH")),task); Thread ...

Selenium in Python encounters difficulty locating web element

I've been attempting to extract posts from a forum I found at this specific URL: The main content I'm trying to pull is located within: <div class="post-content"> However, no matter if I use get element to search by XPATH or CLA ...

Navigating around Security Certificate page on Microsoft Edge using Selenium WebDriver

Is there a way to bypass the Security Certificate page for Microsoft Edge when using Selenium Webdriver with Python? https://i.stack.imgur.com/StSpB.jpg I've tried solutions that have worked for Internet Explorer in the past, following suggestions f ...

Setting a list as a value in a dataframe - a step-by-step guide

My goal is to populate cells in a table with the monthly activity data of GitHub users, organized by years and months (e.g., 2021_01, 2022_10). https://i.stack.imgur.com/BGwfx.jpg The Xpath for this information can be found here: //*[@id="js-contrib ...

Finding an element with Python and Selenium by accessing innerHTML

I am currently navigating my way through Selenium and attempting to create my inaugural script using the Python package. My setup includes: Operating System: Windows 10 Python Version: 3.10.5 Selenium Version: 4.3.0 Up until now, I have managed to accom ...