WebDriver driver=new FirefoxDriver();
driver.get("http://www.grtjewels.com");
driver.findElement(By.id("CollapsiblePanel1txt")).click();
e=( driver.findElement(By.xpath(".//*[#id='CollapsiblePanel1']/div/p[5]")).getAttribute("value"));
System.out.println("The output is " +e);
I have to print the Gold value....Can any one please help me out
It looks like a sync issue
See the use of wait until element is visible below
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.get("http://www.grtjewels.com");
driver.findElement(By.id("CollapsiblePanel1txt")).click();
WebElement e = driver.findElement(By.xpath(".//*[#id='CollapsiblePanel1']/div/p[5]"));
//Waiting for the element to be visible
Wait wait = new WebDriverWait(driver, 10);
wait.until(ExpectedConditions.visibilityOf(e));
System.out.println("The output is " +e.getText());
}
Are you trying to only print the selected values of the element? Did you try doing driver.findElement(By.xpath(".//*[#id='CollapsiblePanel1']/div/p[5]")).getText()
Related
I am trying to port an Xamarin.Forms app to .NET MAUI but have run into the deprecation of Device.StartTimer, whilst this obviously currently still works in MAUI, I am interested to find out what the alternative is?
Currently I have a wrapper class as follows:
public void Start()
{
if (IsRunning)
{
return;
}
var wrapper = new TaskWrapper(Task, IsRecurring, true);
Tasks.Add(wrapper);
Device.StartTimer(Interval, wrapper.RunTask);
}
I tried replacing this with a System.Timers.Timer however this led to the issue of not being able to modify UI elements due to being on the wrong thread? The timer wrapper itself is used in multiple places so I can't use binding for example in this case either.
Is there actually a direct replacement for Device.StartTimer? Any assistance is greatly appreciated.
The Device timer is obsolete in MAUI.
You can create an IDispatcherTimer instance and subscribe to the Tick event like this:
var timer = Application.Current.Dispatcher.CreateTimer();
timer.Interval = TimeSpan.FromSeconds(1);
timer.Tick += (s,e) => DoSomething();
timer.Start();
Depending on the context that you're using the timer in, you should use the MainThread.BeginInvokeOnMainThread() method to update UI elements:
void DoSomething()
{
MainThread.BeginInvokeOnMainThread(() =>
{
//Update view here
});
}
More info on UI main thread:
https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/appmodel/main-thread
IDispatcherTimer timer;
timer = Dispatcher.CreateTimer();
timer.Interval = TimeSpan.FromMilliseconds(1000);
timer.Tick += (s, e) =>
{
label.Text = DateTime.Now.ToString();
};
timer.Start();
https://learn.microsoft.com/en-us/dotnet/maui/user-interface/controls/button#press-and-release-the-button
So currently I'm trying to make a print feature for my Notepad application. I already have a kind of working Print feature, but it prints the full TextArea not only the string that is written into it.
I already tried to make it just print a string, but the PrintJob is not able to handle it, because it needs the actual TextArea, where the Text is written into.
My current Print Stuff:
public void doPrint() {
String toPrint = writeArea.getText();
printSetup(writeArea, Main.primaryStage);
}
private final Label jobStatus = new Label();
private void printSetup(Node node, Stage owner)
{
// Create the PrinterJob
PrinterJob job = PrinterJob.createPrinterJob();
if (job == null)
{
return;
}
// Show the print setup dialog
boolean proceed = job.showPrintDialog(owner);
if (proceed)
{
print(job, node);
}
}
private void print(PrinterJob job, Node node)
{
// Set the Job Status Message
jobStatus.textProperty().bind(job.jobStatusProperty().asString());
// Print the node
boolean printed = job.printPage(node);
if (printed)
{
job.endJob();
}
}
What I want to have:
A print that only shows the String, just like any other notepad application does if you try to print something
What I currently get:
The full textarea with frame.
As I mentioned in the comment you can wrap it into a Text, but then the first line for some reason isn't displayed correctly.
The solution would be to use a Label instead like:
printSetup(new Label(toPrint), Main.primaryStage);
boolean display=driver.findElement(By.cssSelector("input#txtkeyword[placeholder='Job title']")).isDisplayed();=false
boolean select=driver.findElement(By.cssSelector("input#txtkeyword[placeholder='Job title']")).isSelected();=false
boolean enable=driver.findElement(By.cssSelector("input#txtkeyword[placeholder='Job title']")).isEnabled();=true
There are many reasons for an element to not be visible. It could be covered by a pop-up, the DOM could still be loading, you may have to scroll it into view.
For the first instance, take a screenshot on failure and see if the element is covered. I use the following for cucumber-jvm. You can google how to do it for whatever framework you are using.
#After
public void captureScreenshotOnFailure(Scenario scenario){
try {
if (scenario.isFailed() && driver !=null) {
System.out.println("***>> Scenario failed: "+scenario.getStatus());
try {
driver augemented = new Augmenter().augment(webDriver);
byte[] screenshot = ((TakesScreenshot) augemented).getScreenshotAs(OutputType.BYTES);
scenario.embed(screenshot, "image/png");
} catch (Exception e) {
e.printStackTrace();
}
}
} finally {
if (driver !=null) {
driver.quit();
}
}
}
For the DOM not finished loading, wait for it.
Wait<driver> wait_element = new WebDriverWait(driver, 80);
WebElement jobTitleElement = wait_element.until(
ExpectedConditions.visibilityOfElementLocated(By.cssSelector(
"input#txtkeyword[placeholder='Job title']")));
If the wait fails then the element just isn't there.
If the wait succeeds then scroll to the element. If the element was a button you could click() it after the moveToElement(). It is not but including the code just to be complete.
Actions action = new Actions(driver);
action.moveToElement(jobTitleElement).click().build().perform();
In my app, I have a searchbox which allows users to filter as they type. For some reason I can't get an InfinteProgress to properly display while the filtering is being executed.
Here's my code:
Pass 1
public void renderForumList(){
try{
magnify = mStateMachine.findForumSearchIcon(form);
}catch(NullPointerException ex){
System.out.println("User typed additional character in search term before previous term finished executing");
}
InfiniteProgress infi = new InfiniteProgress();
magnify.getParent().replace(magnify, infi, null);
Display.getInstance().invokeAndBlock(new Runnable() {
#Override
public void run() {
for (int i = 0;i < containerStates.length;i++){
if(containerStates[i] != listItems[i].isVisible()){
listItems[i].setHidden(!containerStates[i]);
listItems[i].setVisible(containerStates[i]);
}
}
Display.getInstance().callSerially(new Runnable() {
#Override
public void run() {
mStateMachine.findForumsListComponent(form).animateLayout(200);
mStateMachine.findContainer2(form).replace(infi, magnify, null);
}
});
}
});
}
In this version, the infinite progress shows up in the proper position, but it doesn't spin.
Pass 2
public void renderForumList(){
try{
magnify = mStateMachine.findForumSearchIcon(form);
}catch(NullPointerException ex){
System.out.println("User typed additional character in search term before previous term finished executing");
}
InfiniteProgress infi = new InfiniteProgress();
magnify.getParent().replace(magnify, infi, null);
for (int i = 0;i < containerStates.length;i++){
if(containerStates[i] != listItems[i].isVisible()){
listItems[i].setHidden(!containerStates[i]);
listItems[i].setVisible(containerStates[i]);
}
}
mStateMachine.findForumsListComponent(form).animateLayout(200);
mStateMachine.findContainer2(form).replace(infi, magnify, null);
}
}
}
In this version, the magnifier icon just flashes briefly, but the InfiniteProgress spinner is never visible.
I get the same results on the simulator and on an Android device.
How can I get the InfiniteProgress to spin while the search is taking place?
invokeAndBlock opens a new thread and thus violates the EDT as you access UI components on a separate thread.
Try using callSerially instead to postpone the following code into the next EDT cycle although I'm not sure that will help as everything is still happening on the EDT.
Alternatively I'm guessing the method isVisible takes time, so you can enclose that call alone in invokeAndBlock.
To understand invokeAndBlock check out the developer guide https://www.codenameone.com/manual/edt.html
sometimes when running tests on WebDriver with Javascript turned off, WebDriver crashes due to an ElementNotFound Error when it finds an element, and attempts to click it.
However, the element is clearly there !
After reading this : http://code.google.com/p/selenium/wiki/FrequentlyAskedQuestions#Q:_My_XPath_finds_elements_in_one_browser,_but_not_in_others._Wh
I came to the conclusion that webdriver must not be waiting until the web page has completed loaded. How do I use the Webdriver Wait class ? Can someone provide an example ?
This example was posted on Google Groups. According to Google developers:
1 Use implicit waits. Here the driver will wait up until the designated
timeout until the element is found. Be sure to read the javadoc for the
caveats. Usage:
driver.get("http://www.google.com");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
WebElement element = driver.findElement(By.name("q"));
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
// continue with test...
2 Use the org.openqa.selenium.support.ui.WebDriverWait class. This will
poll until the expected condition is true, returning that condition's result
(if it's looking for an element). This is much more flexible than implicit
waits, as you can define any custom behavior. Usage:
Function<WebDriver, WebElement> presenceOfElementLocated(final By locator) {
return new Function<WebDriver, WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(locator);
}
};
}
// ...
driver.get("http://www.google.com");
WebDriverWait wait = new WebDriverWait(driver, /*seconds=*/3);
WebElement element = wait.until(presenceOfElementLocated(By.name("q"));
Taking nilesh's answer a step further, you can also allow finer-tuned searches (eg, within the context of a WebElement) by using the SearchContext interface:
Function<SearchContext, WebElement> elementLocated(final By by) {
return new Function<SearchContext, WebElement>() {
public WebElement apply(SearchContext context) {
return context.findElement(by);
}
};
}
Execution is performed by a FluentWait<SearchContext> instance (instead of WebDriverWait). Give yourself a nice programming interface by wrapping its execution and necessary exception handling in a utility method (the root of your PageObject type hierarchy is a good spot):
/**
* #return The element if found before timeout, otherwise null
*/
protected WebElement findElement(SearchContext context, By by,
long timeoutSeconds, long sleepMilliseconds) {
#SuppressWarnings("unchecked")
FluentWait<SearchContext> wait = new FluentWait<SearchContext>(context)
.withTimeout(timeoutSeconds, TimeUnit.SECONDS)
.pollingEvery(sleepMilliseconds, TimeUnit.MILLISECONDS)
.ignoring(NotFoundException.class);
WebElement element = null;
try {
element = wait.until(elementLocated(by));
}
catch (TimeoutException te) {
element = null;
}
return element;
}
/**
* overloaded with defaults for convenience
*/
protected WebElement findElement(SearchContext context, By by) {
return findElement(context, by, DEFAULT_TIMEOUT, DEFAULT_POLL_SLEEP);
}
static long DEFAULT_TIMEOUT = 3; // seconds
static long DEFAULT_POLL_SLEEP = 500; // milliseconds
Example usage:
WebElement div = this.findElement(driver, By.id("resultsContainer"));
if (div != null) {
asyncSubmit.click();
WebElement results = this.findElement(div, By.id("results"), 30, 500);
if (results == null) {
// handle timeout
}
}
Fluent Wait - Best approach as it's the most flexible and configurable on the fly (has ignore exceptions option, polling every, timeout):
public Wait<WebDriver> getFluentWait() {
return new FluentWait<>(this.driver)
.withTimeout(driverTimeoutSeconds, TimeUnit.SECONDS)
.pollingEvery(500, TimeUnit.MILLISECONDS)
.ignoring(StaleElementReferenceException.class)
.ignoring(NoSuchElementException.class)
.ignoring(ElementNotVisibleException.class)
}
Use like so:
WebElement webElement = getFluentWait().until(x -> { return driver.findElement(elementBy); } );
Explicit Wait - Well it's the same as FluentWait but with pre-configured pollingEvery and the type of Wait e.g. FluentWait<WebDriver> (faster to use):
WebDriverWait wait = new WebDriverWait(driver, 30000);
WebElement item = wait.until(ExpectedConditions.visibilityOfElementLocated(yourBy));
ImplicitWait - Not recommended as it is configured once for all your session. This also is used for every find element and waits for presence only (no ExpectedConditions etc...):
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);