I am trying to highlight (around the border) element that is found in selenium webdriver using C#. I have search the net all i found was java codes, but need it in C#.
or is there any other way to do it.
thanks
There is no native way to do this, but because Selenium allows you use to execute Javascript, you can accomplish it just with a little more work:
Therefore the question becomes "how do I change an elements borders in Javascript?"
If you use jQuery it's a little bit easier, you could find the element and then set some border properties. jQuery has a neat little css property that allows you to pass in a JSON dictionary of values, it will handle setting them all for you, an example would be like:
jQuery('div.tagged > a:first').css({ "border-width" : "2px", "border-style" : "solid", "border-color" : "red" });
That would find an element, and set it's border to be solid at 2px wide with a border colour of red.
However, if you already have an IWebElement instance of the element (likely) you can take the 'finding' responsibility out of jQuery/Javascript and make it simpler again.
This would be executed something like:
var jsDriver = (IJavaScriptExecutor)driver;
var element = // some element you find;
string highlightJavascript = #"$(arguments[0]).css({ ""border-width"" : ""2px"", ""border-style"" : ""solid"", ""border-color"" : ""red"" });";
jsDriver.ExecuteScript(highlightJavascript, new object[] { element });
If you just want basic Javascript, then you could make use of the .cssText property, which allows you to give a full string of CSS styles instead of adding them individually (although I don't know how supported it is cross browser):
var jsDriver = (IJavaScriptExecutor)driver;
var element = // some element you find;
string highlightJavascript = #"arguments[0].style.cssText = ""border-width: 2px; border-style: solid; border-color: red"";";
jsDriver.ExecuteScript(highlightJavascript, new object[] { element });
(Although there are more ways, I've just gone for the most verbose to make it clearer)
C# Extension Method: Highlights and Clears in 3 seconds.
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Remote;
using System.Reactive.Linq;
public static class SeleniumUtil
{
public static void Highlight(this IWebElement context)
{
var rc = (RemoteWebElement)context;
var driver = (IJavaScriptExecutor)rc.WrappedDriver;
var script = #"arguments[0].style.cssText = ""border-width: 2px; border-style: solid; border-color: red""; ";
driver.ExecuteScript(script, rc);
Observable.Timer(new TimeSpan(0, 0, 3)).Subscribe(p =>
{
var clear = #"arguments[0].style.cssText = ""border-width: 0px; border-style: solid; border-color: red""; ";
driver.ExecuteScript(clear, rc);
});
}
}
Thanks Arran i just modified your answer..
var jsDriver = (IJavaScriptExecutor)driver;
var element = //element to be found
string highlightJavascript = #"arguments[0].style.cssText = ""border-width: 2px; border-style: solid; border-color: red"";";
jsDriver.ExecuteScript(highlightJavascript, new object[] { element });
it works perfectly...
thanks once again.
Write below JavaScript Executor code in your Class file
public void elementHighlight(WebElement element) {
for (int i = 0; i < 2; i++) {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript(
"arguments[0].setAttribute('style', arguments[1]);",
element, "color: red; border: 5px solid red;");
js.executeScript(`enter code here`
"arguments[0].setAttribute('style', arguments[1]);",
element, "");
}
Call the above method from Selenium test case to highlight a web page element. Check out below code which shows how it is done. elementHighlight method is called with searchBox as an argument.
#Test
public void GoogleSearch() throws Exception, SQLException {
driver.findElement(By.xpath("//center/div[2]")).click();
WebElement searchBox = driver.findElement(By.xpath("//div[3]/div/input"));
elementHighlight(searchBox);
driver.findElement(By.xpath("//div[3]/div/input")).clear();
driver.findElement(By.xpath("//div[3]/div/input")).sendKeys("Test");
driver.findElement(By.xpath("//button")).click();
}
On executing the above test, Selenium test will highlight the search box on Google home page. You can reuse elementHighlight method for highlighting any elements on web page.
Related
What my code is doing:
creates an img tag that changes the image every 3 seconds.
background image is static
currently, we have a dynamic img tag that's changing every 3 seconds on top of a static background. reason being it was a test to see I could make it dynamic
What I want to do:
background-image inside the script tag to change and somehow make the URL() dynamic. Background image should change very 3 seconds
<div class="text-center background">
<p>come content</p>
<img id="image" src="~/images/baseball.jpg">
<script type = "text/javascript">
var image = document.getElementById("image");
var currentPos = 0;
var images = ["/images/baseball.jpg", "/images/basketball.jpg", "/images/football.jpg", "/images/soccerball.jpg"], i = 0;
function changeimage()
{
if (++currentPos >= images.length)
currentPos = 0;
image.src = images[currentPos];
}
setInterval(changeimage, 3000);
</script>
</div>
<style>
.background{
background-image: url(/images/basketball.jpg); //<<<-----this line needs to be dynamic
background-repeat: no-repeat;
background-size: cover;
height: 1000px;
}
</style>
I understand I may need to restructure my code a little. I just don't know how to go about doing it with a background. with a normal image tag it's easy because I simply reassign a new image path to the old Id.
Additional information:
framework: .netcore-mvc
bootstrap: 4.6
Just set the style of the background element, its practically the same as your current solution:
There's a good solution for this on SO: [Changing background-image with JavaScript]
<div id="background" class="text-center background">
<p>come content</p>
<script type = "text/javascript">
var background = document.getElementById("background");
var currentPos = 0;
var images = ["/images/baseball.jpg", "/images/basketball.jpg", "/images/football.jpg", "/images/soccerball.jpg"], i = 0;
function changeimage()
{
if (++currentPos >= images.length)
currentPos = 0;
background.style.backgroundImage = "url(" + images[currentPos] + ")";
}
setInterval(changeimage, 3000);
</script>
</div>
This solution is pure HTML Javascript, there are image carousel controls and component based solutions that will help if you want to run the timing logic on the server, but this javascript is a very simple solution to the problem.
I searched for some time on this question and couldn't find a working answer anywhere.
I have an asp DropDownList that gets disabled and enabled based on whether the form is in view mode or not. The problem I was having is when the DropDownList.Enabled = false the text is hard to read(grey on lightgrey).
I solved the issue by passing the DropDownList to some methods.
public void DisableDDL(ref DropDownList DDL)
{
DDL.BackColor = System.Drawing.Color.LightGray;
foreach (ListItem i in DDL.Items)
{
if (i != DDL.SelectedItem)
{
i.Enabled = false;
}
}
}
public void EnableDDL(ref DropDownList DDL)
{
DDL.BackColor = System.Drawing.Color.White;
foreach (ListItem i in DDL.Items)
{
i.Enabled = true;
}
}
Is there another way to do this?
I tried using css but that didn't work.
<style>
.disabledStyle
{
color: black;
}
</style>
myDDl.CssClass = "disabledStyle";
There is no readonly property for the dropdownlist control. But you can move the focus to another control when it receives the focus and that will prevent it from being changed and leave the text black.
You need to apply the style to each individual ListItem, and not to the DropDownList itself
I have just put in a dropdownlist and put it to enabled false in the controller, then I found out that it has a class called "aspNetDisabled", I have tried to use CSS to change color on it, it works perfectly.
<style>
.aspNetDisabled
{
color: #FFF;
background-color: #000;
}
</style>
In the code, if you put the dropdownlist, "ddl.enabled = false", it will be like this:
<select name="DropDownList1" id="DropDownList1" disabled="disabled" class="aspNetDisabled"></select>
If the dropdownlists are surrounded by a div with a class, use the class to define the disabled ones:
<style>
.MyCssClass[disabled]
{
color: #FFF;
background-color: #000;
}
</style>
Or try
:disabled,[disabled]
{
-ms-opacity: 0.5;
opacity:0.5;
}
</style>
As said in here:
http://forums.asp.net/t/2028164.aspx?IE+11+disabled+buttons+links+not+shown+as+greyed+out
The simplest way to do that:
<style>
[disabled] { /* Text and background colour, medium red on light yellow */
color:#933;
background-color:#ffc;
}
</style>
I need an assistance, how can I select a value from a drop down list, I am programming on C# with Selenium, and I am always getting the following error:
Element should have been select but was span
My code is:
internal static void SelectDD()
{
SelectElement xxx= new SelectElement(driver.FindElement(By.XPath("/html/body/div[1]/section/div[1]/div[2]/section/div/section/div[2]/div[2]/div/div[2]/div[1]/div/div[2]/div/div/a/span[1]")));
xxx.SelectByIndex(1);
}
HTML:
<span class="select2-hidden-accessible" role="status" aria-live="polite"></span> <span class="select2-hidden-accessible" role="status" aria-live="polite"></span> <span class="select2-hidden-accessible" role="status" aria-live="polite"></span>
<div id="select2-drop-mask" class="select2-drop-mask" style="display: block;"></div>
<div id="select2-drop" class="select2-drop select2-display-none select2-drop-auto-width select2-drop-active select2-drop-above" style="left: 361.583px; top: 472.1px; bottom: auto; display: block; width: 262px;"></div>
</body>
First of all SelectElement can only be used with the element with Select tag. This is a div and SelectElement class does not apply here.
Try finding the element and just performing a click as follows:
IWebElement element = driver.FindElement(By.Id("select2-drop"));
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
js.ExecuteScript("arguments[0].click();", element);
The problem is the dropdown is not actually a drop down. Select Element can only work with element the html should be like below.
A work around would be to create a custom method which will suit the html structure you have now.
var spans = driver.FindElements({selector});
foreach(var span in spans)
{
if(span.Text == "some")
span.Click();
}
If you know the text of the DropDown, you can use method SendKeys(string text) of IWebElement
internal static void SelectDD()
{
IWebElement xxx= driver.FindElement("");
xxx.SendKeys("Text Of The Dropdown");
}
I am trying to simulate a click on a image in IE through C# using SHDocVw but have a problem. My program does not seem to find the img in the code.. Here is what I got:
SHDocVw.ShellWindows AllBrowsers = new SHDocVw.ShellWindows();
foreach (SHDocVw.InternetExplorer ieInst in AllBrowsers)
{
mshtml.IHTMLDocument2 htmlDoc = ieInst.Document as mshtml.IHTMLDocument2;
string html = htmlDoc.body.outerHTML;
foreach (mshtml.HTMLImg imgElement in htmlDoc.images)
{
if (imgElement.nameProp.ToString().Equals("icon_go.GIF"))
{
imgElement.click();
}
}
}
Here is a part of the html code im working on:
<TD align=center><INPUT title="View Detail Statistics" style="BORDER-LEFT-WIDTH: 0px; HEIGHT: 14px; BORDER-RIGHT-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; BORDER-TOP-WIDTH: 0px; WIDTH: 14px" src="../App_Themes/Company/Images/icon_go.GIF" type=image name=process1></TD></TR>
A problem is that the picture IS a button on the website but I dont know how to press it through the C# code.
Is there maybe another way to select the button? Like through the name "process1" instead of going for the image name?
As pointed out in your comment you are looping IMG but you should be looping INPUT:
foreach (IHTMLElement element in htmlDoc.all)
{
var input = element as IHTMLInputImage;
if (input != null && Path.GetFileName(input.src).Equals("icon_go.GIF", StringComparison.OrdinalIgnoreCase))
{
((IHTMLElement)input).click();
}
}
I have C# / XAML win store app which receives various data from json. one piece of it - html string.
I display that string using WebView.NavigateToString
However I don't see how can I style it. Normally I would use blend to get default style and then edit it. But Blend doesn't let me style WebView.
I ended up wrapping the json html into
<body style='background-color:black;color:white' />
but this approach doesn't let me use theming which the rest of the application does.
What is the 'proper' way to style and / or format content of the WebView?
Another solution is making a WebViewContentHelper (or so) class. You may pass the theme and style the CSS according to that. For example:
string content = WebViewContentHelper.WrapHtml(originalHtmlString, backGroundColor, webView.ActualHeight);
webView.NavigateToString(content);
You can adapt this class that already copies the Font styling from Windows 8 and gives you horizontal scrolling, also arranges content in columns, just as ItemDetails Template:
class WebContentHelper
{
public static string HtmlHeader(double viewportWidth, double height) //adapt parametres
{
var head = new StringBuilder();
head.Append("<head>");
head.Append("<meta name=\"viewport\" content=\"initial-scale=1, maximum-scale=1, user-scalable=0\"/>");
head.Append("<script type=\"text/javascript\">"+
"document.documentElement.style.msScrollTranslation = 'vertical-to-horizontal';"+
"</script>"); //horizontal scrolling
//head.Append("<meta name=\"viewport\" content=\"width=720px\">");
head.Append("<style>");
head.Append("html { -ms-text-size-adjust:150%;}");
head.Append(string.Format("h2{{font-size: 48px}} "+
"body {{background:white;color:black;font-family:'Segoe UI';font-size:18px;margin:0;padding:0;display: block;"+
"height: 100%;"+
"overflow-x: scroll;"+
"position: relative;"+
"width: 100%;"+
"z-index: 0;}}"+
"article{{column-fill: auto;column-gap: 80px;column-width: 500px; column-height:100%; height:630px;"+
"}}"+
"img,p.object,iframe {{ max-width:100%; height:auto }}"));
head.Append(string.Format("a {{color:blue}}"));
head.Append("</style>");
// head.Append(NotifyScript);
head.Append("</head>");
return head.ToString();
}
public static string WrapHtml(string htmlSubString, double viewportWidth, double height)
{
var html = new StringBuilder();
html.Append("<html>");
html.Append(HtmlHeader(viewportWidth,height));
html.Append("<body><article class=\"content\">");
html.Append(htmlSubString);
html.Append("</article></body>");
html.Append("</html>");
return html.ToString();
}
}
You cannot style/extend webview apparently, Webview is not a derivative of control subclass (it does not have a control template) and is rather hosted in its own HWND. You are probably better off using webviewbrush. See this sample
You can style like this
public static string Scape(string htmlContent, string fontColor)
{
var htm = "<html> <head> <script type=\"text/javascript\"></script> <style> body { color: "+ fontColor +"; } </style> </head> <body>" + htmlContent +"</body></html>";
return htm;
}