Selenium C# how to get text in IWEbElement - javascript

I am trying to fill in a text-field on a website for which the id changes every time the website is opened. To circumvent this, I look up the webelement by it's class name and this seems to work well as I am able to click on it through
currentWebElement.Click();
however, when I try to fill in the edit text box through
currentWebElement.SendKeys("51");
nothing happens (even more so, focus is lost)
I have searched a lot to see what the problem is but have not been able to find a solution so I was wondering if someone here can point me in the right direction. What I have tried so far:
1) I was working in chrome but since this seems to be a common problem with sendKeys I have swithed to ie, alas the problem persisted. I have tried migrating to firefox but did not succeed as I cannot seem to locate the binary path to firefox.exe but this should be addressed in a different question. So the problem occurs both in chrome and IE.
2) Using javascript to send the command as I have found this suggestion in other questions that were answered on this website:
driver.ExecuteScript("arguments[0].value = '51'", currentWebElement);
directly but also implementing it as a function did not work:
private static object setValue(this IWebDriver driver, IWebElement element, String value) {
return ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].value = arguments[1]", element, value);
}
// and then calling it in my code:
setValue(driver, currentWebElement, "51");
all implementations did not give me errors nor warnings (I managed to get rid of those during the process), but none of them give the desired result i.e. the box keeps remaining empty which is really starting to bug me!

Try the below code. I have used XPATH to sendKeys in the field(FYI the PRMT_TB part of the id doesn't change, even if the rest part does each time, hence the xpath):
var currentWebElement = driver.FindElement(By.XPath("//input[starts-with(#id,'PRMT_TB')]"));
currentWebElement.SendKeys("51");
OR
In case the above doesn't work, please try the below code too
var currentWebElement = driver.FindElement(By.XPath("//td[#class='clsTextWidgetParseError']/input"));
currentWebElement.SendKeys("51");

By byCss = By.CssSelector(".clsTextWidgetParseError>input");
var element = Driver.FindElement(byCss );
element.Clear();
element.SendKeys(value);
I am assuming you are using wrong selector. If this throws any exception provide me the stack trace please

Related

Grab input value after send key and console log the value Selenium Webdriver

I am currently working on a project where I need to integrate the use of the Selenium Webdriver. I am using the Chrome implementation of Web Driver and running it via Javascript. I am currently testing a simple quantity input form. I am having trouble with a particular aspect of this project and that is ... I need the test to run through the form and put in different values everytime. I am placing the values via the sendKeys function. Now the trouble starts here... I need to grab the value that the sendKeys function inputs into the field and console.log a message depending on the value.
If the value is over a 100 I need the test to console.log the message "Exceeds 100".
If the value is less than 0 I need it to console.log the message "Below 0".
And if there is no value I need it to console.log the message "No input".
It runs through and puts in new values just fine. But the issue has been grabbing the value and console.logging a message depending on the value. I've tried many different options but there's just so little documentation related to this exact topic. I will link my code below, and I appreciate any input you guys may have... because it has me stumped unfortunately.
Also I am curious if this can be done using assertions in any way...
Test File Below:
https://gist.github.com/anonymous/89a84dbc15ba4088719400be1f359045
There is a method getAttribute(String attrName) it will accept a string parameter, pass attribute name against which value got set.
for example:
WebElement element =driver.findElement("your unique element locator");
String valueText=element.getAttribute("value");
about the answer above me - you should try adding a .getText(), So the attribute value would become a String.
WebElement element = driver.findElement("your unique element locator");
String valueText = element.getAttribute("value").getText();
Please add the full error message, A screenshot of the console would be good.

Print html to a surface to be copied

I stored an table's html as a text, using this code.
var Data = document.getElementsByClassName("result")[0].innerHTML;
I am able to observe the selected part using console.log, however, I wish to extract this data to be copied and used outside.
So I tried alert(Data), but it does not offer a good surface to copy the data (it does work though, however I cannot use right click on the pop-up window)
I also tried to programmatically copy the data to the clipboard, but it seems, it only works on selected text data.
Is there a better way to extract such data to be used outside ?
Note: I am using a firefox bookmark to execute javascript. But I expect the code to work also in the other browsers.
Edit: I tried the method suggested in the comments, however in firefox, I got an error.
document.execCommand(‘cut’/‘copy’) was denied because it was not called from inside a short running user-generated event handler.
So rather than copying with that command, printing to a surface seems a better choice, if possible. The linked question does not solve my issue.
Edit2: window.prompt did a much better job, however it rocked my world by pressing the text to a single line. I still should be able to parse it programmatically, but if there is a better answer, I wish to learn it.
Below is my solution to keep multiple lines.
It creates one temp 'textarea', then remove it after select()->copy.
function triggercopy() {
var target_obj = document.getElementById('test1');
var copy_text = target_obj.innerHTML; //replace with your actual data.
var hidden_obj = document.createElement("textarea");
hidden_obj.value = copy_text;
document.body.insertBefore(hidden_obj,target_obj);
console.log('prepare:' + copy_text);
hidden_obj.select();
document.execCommand("copy");
document.body.removeChild(hidden_obj);
console.log('already copied:' + copy_text);
}
Text3as
dfsadf
<a id="test1" onclick="triggercopy();">Text3as
dfsadf</a>
I found two methods best suit my interests.
First, window.prompt:
var Data = document.getElementsByClassName("result")[0].innerHTML;
function copyToClipboard(text) {
window.prompt("Copy data.", text);
}
copyToClipboard(Data)
This is a good method, taken from a suggested answer. This puts the data into a single-line text field. And in an interesting manner, when written without a function, executes document.write(Data) when clicked OK, this does not happen when written in a function as above.
Second, document.write:
var target = document.getElementsByClassName("resultTable striped")[0].outerHTML;
document.open('text/plain');
document.write(target);
I first tried to open a new tab with the desired content, however encountered with the issue of pop-up blockers and non-plain text html data (formatted html instead of the desired table html data). This solves both issues.

javascript localstorage

So, here's my code:
localStorage.setItem("nhac",for(p=0;p<opener.document.getElementsByName('link').length;p++){opener.document.getElementsByName('link').item(p).style.backgroundColor})
I'm so confused i can't think anymore xD, I've been trying all day long to make this work, i can't even explain it,sorry.
I have a popup which i opened from the main page. From the pop up window, im retrieving the elements from which i want to save the background-color so, by saving it in localstorage, it will always remain like that.
I've done others that work well, like this
localStorage.setItem("color_chosen2", opener.document.getElementById('header').style.color);
I don't know why it doesn't work, can anyone help me? It gives me some kind of error( the first one)
thanks
Edit:(sorry, I was in a hurry when i posted this)
The error it gives is "SyntaxError: syntax error"
(I'm using firefox, by the way)
Using the javascript console, this code
for(p=0;p<opener.document.getElementsByName('link').length;p++){opener.document.getElementsByName('link').item(p).style.backgroundColor}
returns the background color of the elements perfectly, but when I try to use it as the value in localStorage , it gives an error.
And no, there's no problem with the syntax localStorage.setItem, it's how it is, thanks.
Edit2: if you need to see how it works better, here's my website. the pop-up opens from the link in the bottom center.
You are trying to set a for loop into a setter which accepts a String. You must set each of the styles individually and with a unique key value.
Also, I don't think item is a method...
Try this...
items = opener.document.getElementsByName('link');
for ( p = 0; p < items.length; p++ ){
localStorage.setItem( p + 'nhac', items[p].style.backgroundColor );
}
Well, noone really effectively helped me, but at least 2 people tried to help, so thank you.
Anyway, i don't know how, I had an idea and the code works now...to anyone interested:
if(localStorage.getItem("color_chosen3")){
for(p=0;p<document.getElementsByName('link').length;p++){document.getElementsByName('link').item(p).style.backgroundColor=localStorage.getItem("color_chosen3")}}}
Problem solved, question closed...whatever. thanks

IE Object doesn't support this property or method

This is probably the beginning of many questions to come.
I have finished building my site and I was using Firefox to view and test the site. I am now IE fixing and am stuck at the first JavaScript error which only IE seems to be throwing a hissy about.
I run the IE 8 JavaScript debugger and get this:
Object doesn't support this property or method app.js, line 1 character 1
Source of app.js (first 5 lines):
var menu = {};
menu.current = "";
menu.first = true;
menu.titleBase = "";
menu.init = function(){...
I have tested the site in a Webkit browser and it works fine in that.
What can I do to fix this? The site is pretty jQuery intensive so i have given up any hope for getting it to work in IE6 but I would appreciate it working in all the others.
UPDATE: I have upload the latest version of my site to http://www.frankychanyau.com
In IE8, your code is causing jQuery to fail on this line
$("title").text(title);
in the menu.updateTitle() function. Doing a bit of research (i.e. searching with Google), it seems that you might have to use document.title with IE.
Your issue is (probably) here:
menu.updateTitle = function(hash){
var title = menu.titleBase + ": " + $(hash).data("title");
$("title").text(title); // IE fails on setting title property
};
I can't be bothered to track down why jQuery's text() method fails here, but it does. In any case, it's much simpler to not use it. There is a title property of the document object that is the content of the document's title element. It isn't marked readonly, so to set its value you can simply assign a new one:
document.title = title;
and IE is happy with that.
It is a good idea to directly access DOM properties wherever possible and not use jQuery's equivalent methods. Property access is less troublesome and (very much) faster, usually with less code.
Well, your line 1 certainly looks straight forward enough. Assuming the error line and number is not erroneous, it makes me think there is a hidden character in the first spot of your js file that is throwing IE for a fit. Try opening the file in another text editor that may support display of normally hidden characters. Sometimes copying/pasting the source into a super-basic text-editor, like Notepad, can sometimes strip out non-displayable characters and then save it back into place directly from Notepad.

How to increase speed of getElementById() function on IE or give other solutions?

I have a project using Javascript parse json string and put data into div content.
In this case, all of itemname variables is the same div's id.
If variable i about 900, I run this code in Firefox 3 for <10ms, but it run on IE 7 for >9s, IE process this code slower 100 times than Firefox
I don't know what happen with IE ?
If I remove the line document.getElementById(itemname), speed of them seems the same.
The main problem arcording to me is document.getElementById() function?
Could you show me how to solve this prolem to increase this code on IE ?
Thank in advance.
var i = obj.items.length-2;
hnxmessageid = obj.items[i+1].v;
do{
itemname = obj.items[i].n;
itemvalue = obj.items[i].v;
document.getElementByid(itemname);
i--;
}while(i>=0);
Are you really noticing any latency?
gEBI is natively very very fast, I don't think you can avoid it anyway for what you're doing. Could you provide a low-down of what you're doing precisely? It looks like you're using a loop, but can you post exactly what you're doing inside of the loop, what your common goal of the script is?
document.getElementByid(itemname) is the fastest way to get a single element from the DOM in any real application you will sould not see any problems with using it, if you do see a problem you need to rethink you code a little it possible to acomplish any task with just a handfull of calls for this method. You can present you full problem if you like so I could show you an example
At least cache the reference to document:
var doc = document;
for(;;) {
doc.getElementById(..);
}

Categories

Resources