Summary: In the url below, please click the reply button. Then, a popup will appear and hide the reply button. When you click a blank area or on the paragraph containing 'post id:', the popup disappears and you can see the reply button again. I want to do these things using the code below.
Problem: None of the last 3 method calls in main make the popup disappear. What is wrong with my code and how do I make it work ?
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
public class Temp {
private static final WebDriver browser = new ChromeDriver();
private static String reply_btn_xpath = "//button[contains(concat(\" \", normalize-space(#class), \" \"), \" "
+ "reply_button" + " \")]";
private static By reply_btn_loc = By.xpath(reply_btn_xpath);
private static String url = "https://sfbay.craigslist.org/pen/apa/5764613878.html";
public static void main(String[] args) {
browser.get(url);
WebElement reply = browser.findElement(reply_btn_loc);
reply.click();
WebElement post_id = browser.findElement(By.xpath("//p[contains(., 'post id:')]"));
post_id.click();
click_with_actions(post_id);
click_with_js(post_id);
}
public static void click_with_actions(WebElement element) {
Actions actions = new Actions(browser);
actions.moveToElement(element).click().perform();
}
public static void click_with_js(WebElement element) {
((JavascriptExecutor) browser).executeScript("arguments[0].click();", element);
}
}
Apparently, it is advised not to use java.awt.Robot in VMs or CI to do the clicks because they don't have real keyboards. Java awt.Robot not working inside a virtual machine?
I tried Robot also in the above code and it did not work.
public static void click_with_robot(WebElement element, int x, int y) {
Robot bot = null;
try {
bot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
Point location = element.getLocation();
int x_loc = location.getX() + x;
int y_loc = location.getY() + y;
bot.mouseMove(x_loc, y_loc);
bot.mousePress(InputEvent.BUTTON1_MASK);
bot.mouseRelease(InputEvent.BUTTON1_MASK);
}
Related
I need your help I want to paginate through a table an store the values of it untill "Next Button" disables.
Although storing values is not ossible its ok. But help me in pagination I want to click on the button it the next button untill it is not disabled .Please help me. I am on a internship
Java Code:
package Onsight.Framework;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import com.github.javafaker.Faker;
import avdhut.onsight.commonutils.BaseComponenets;
import avdhut.onsight.pageobject.HomePage;
import avdhut.onsight.pageobject.LoginPage;
import io.github.bonigarcia.wdm.WebDriverManager;
public class Webtable extends BaseComponenets {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
String urlString = "https://oinsightsvm1.westindia.cloudapp.azure.com:444/ctsOInsightsBMS/res/createReport.html";
String userEmailString = "User66";
String userPassword = "Avdhut#5201";
String titleString;
String textString="Clarita";
Faker faker = new Faker();
WebDriverManager.chromedriver().setup();
ChromeOptions options = new ChromeOptions();
// options.addArguments("--ignore-ssl- errors=yes");
options.addArguments("--ignore-certificate-errors");
WebDriver driver = new ChromeDriver(options);
driver.get(urlString);
LoginPage loginPage = new LoginPage(driver);
loginPage.login_username(userEmailString);
loginPage.click0nsubmit();
loginPage.EnterPassword(userPassword);
loginPage.click0nsubmit();
HomePage homePage = new HomePage(driver);
// homePage.view_report_values(textString);
IsVisible(baseTableBy);
WebElement baseTable=driver.findElement(baseTableBy);
List<WebElement> table_roWebElement=baseTable.findElements(report_name_rowsBy);
for (WebElement webElement : table_roWebElement) {
if (webElement.getText().contains(report_title)) {
System.out.println(true);
IsClickable(viewBy);
System.out.println(webElement.getText());
webElement.findElement(viewBy).click();
IsClickable(view_dataBy);
driver.findElement(view_dataBy).click();
while (IsVisible(paginateBy)) {
IsClickable(paginateBy);
driver.findElement(paginateBy).click();
}
} else {
}
}
}
//tr[class='odd'] em[class='fa fa-table']
Html:
After logging in, once you reach the table which contains the list of reports, add the below code and try:
Thread.sleep(2000);
// to close the toast message, if the toast message does not appear, comment the below line
driver.findElement(By.xpath(".//button[#class='toast-close-button']")).click();
boolean flag = true;
// below while loop will click the 'NEXT' button until it is disabled
while (flag) {
WebElement nextBtn = driver.findElement(By.id("query-table_next"));
if (!nextBtn.getAttribute("class").contains("disabled")) {
nextBtn.click();
Thread.sleep(1000);
} else {
flag = false;
System.out.println("In the last page");
}
}
How to debug a JavaFX webview?
I find two ways,
one is to attach external chrome debugger to JavaFX webview.
Another is to inject firebug javascript.
Method#1 seems to use a bit of hacks like set access to private fields etc.
Method#2 depends on firebuglite which seems to be obsolete now.
How should this be done in 2022. Are there any other methods, or better methods?
I am trying firebug lite approach as of now, and have made the javascript part of the maven project and trying to inject it as a string versus an external URL, because firebug seems to be properly public hosted nowhere now.
Refering to https://stackoverflow.com/a/18396900/2448015
This is where I am right now :
package xyz.jphil.internal_browser;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpServer;
import java.net.InetSocketAddress;
import javafx.scene.web.WebEngine;
import netscape.javascript.JSObject;
/**
*
* #author Ivan
*/
public class WebkitDebugUtils {
private static int resourcesPort = 0;
public static void createHttpServerForLocalFiles() {
int portStart = 64321, endPort = 65534;
resourcesPort = portStart + (int) ((endPort * 1d - portStart * 1d) * Math.random());
System.out.println("Starting internal server on " + resourcesPort);
try {
HttpServer server = HttpServer.create(new InetSocketAddress(resourcesPort), 0);
HttpContext context = server.createContext("/");
context.setHandler((req) -> {
try (req) {
var p = req.getRequestURI();
System.out.println("Serving # localhost:"+resourcesPort+" "+p);
var s = WebkitDebugUtils.class.getResourceAsStream(p.toString()).readAllBytes();
req.sendResponseHeaders(200, s.length);
req.getResponseBody().write(s);
}catch(Exception a){
a.printStackTrace();
}
});
server.start();
} catch (Exception e) {
e.printStackTrace();
}
}
public static class JavaBridge {
public void log(String text) {
System.out.println(text);
}
}
// Maintain a strong reference to prevent garbage collection:
// https://bugs.openjdk.java.net/browse/JDK-8154127
private final static JavaBridge bridge = new JavaBridge();
public static void enableDebug(final WebEngine e) {
JSObject window = (JSObject) e.executeScript("window");
window.setMember("java", bridge);
e.executeScript("""
console.log = function(message)
{
java.log(message);
};""");
e.executeScript("console.log('console.log enabled');");
}
public static void enableFirebug(final WebEngine e) {
var firebugurl = "http://localhost:"+resourcesPort+"/firebug-lite/firebug-lite.js";
//https://raw.githubusercontent.com/stefanXO/firebug-lite/master/firebug-lite.js
//https://lupatec.eu/getfirebug/firebug-lite-compressed.js
var script= """
console.log("Inside script block");
if (!document.getElementById("FirebugLite")) {
E = document["createElement" + "NS"] && document.documentElement.namespaceURI;
E = E ?
document["createElement" + "NS"](E, "script") :
document["createElement"]("script");
E["setAttribute"]("id", "FirebugLite");
E["setAttribute"]("src", "{$firebugurl}#startOpened");
E["setAttribute"]("FirebugLite", "4");
(
document["getElementsByTagName"]("head")[0]
||
document["getElementsByTagName"]("body")[0]
).appendChild(E);
E = new Image();
E["setAttribute"]("src", "{$firebugurl}#startOpened");
}
console.log("executed script block");
""".replace("{$firebugurl}", firebugurl);
System.out.println("+++firebug thing+++");
System.out.println(script);
System.out.println("---firebug thing---");
e.executeScript(script);
}
}
Main method of the application
//...
public static void main(String[]args){
WebkitDebugUtils.createHttpServerForLocalFiles();
launch(args);
}
//...
In the JavaFx Stage initializing code section
#Override
public void start(final Stage primaryStage) throws Exception {
// ....
wv = new WebView();
// ....
javafx.scene.web.WebEngine e = wv.getEngine();
// ....
e.getLoadWorker().stateProperty().addListener((ov, t, t1) -> WebkitDebugUtils.enableDebug(e));
e.documentProperty().addListener((ov, t, t1) -> WebkitDebugUtils.enableFirebug(e));
// ....
}
I am serving the files for firebug from the resources folder of the jar
Snippter of the custom firebug.js file
console.log("inside firebug-lite");
(function(){
//...
//firebug lite 1.4.0 code
//..
})();
console.log("outside firebug-lite");
Output
Starting internal server on 65148
console.log enabled
console.log enabled
// some application specific output
+++firebug thing+++
if (!document.getElementById("FirebugLite")) {
E = document["createElement" + "NS"] && document.documentElement.namespaceURI;
E = E ?
document["createElement" + "NS"](E, "script") :
document["createElement"]("script");
E["setAttribute"]("id", "FirebugLite");
E["setAttribute"]("src", "http://localhost:65148/firebug-lite/firebug-lite.js#startOpened");
E["setAttribute"]("FirebugLite", "4");
(
document["getElementsByTagName"]("head")[0]
||
document["getElementsByTagName"]("body")[0]
).appendChild(E);
E = new Image();
E["setAttribute"]("src", "http://localhost:65148/firebug-lite/firebug-lite.js#startOpened");
}
---firebug thing---
Inside script block
executed script block
Serving # localhost:65148 /firebug-lite/firebug-lite.js
// some application specific output
console.log enabled
Summary:
nothing is happening, nothing is showing up in the console, I don't know the error, firebug is not even opening.
Update2:
I think I am using the wrong version of firebug 1.5 or something
and the old version I don't see any HTML file and thus it is dependent on the default website which is down at the moment.
You can simply inject firebug-lite after loading your webpage.
I've tested on windows 10 with correto 18.0.2 JDK.
Here's an example: (Page can take some time to load)
package com.example.demo;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javafx.scene.web.WebEngine;
import javafx.concurrent.Worker.State;
public class HelloApplication extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage myStage) {
System.out.println("Demo for firebugLite");
WebView myWebView = new WebView();
myWebView.minHeight(1050);
myWebView.prefWidth(1950);
myWebView.prefHeight(1070);
myWebView.minWidth(1050);
final WebEngine myWebEngine = myWebView.getEngine();
myWebEngine.getLoadWorker().stateProperty()
.addListener((obs, oldValue, newValue) -> {
if (newValue == State.SUCCEEDED) {
System.out.println("finished loading");
myWebEngine.executeScript("var firebug=document.createElement('script');firebug.setAttribute('src','https://lupatec.eu/getfirebug/firebug-lite-compressed.js');document.body.appendChild(firebug);(function(){if(window.firebug.version){firebug.init();}else{setTimeout(arguments.callee);}})();void(firebug);");
}
});
myWebEngine.load("https://lupatec.eu/getfirebug/");
VBox myBox = new VBox(myWebView);
Scene myScene = new Scene(myBox, 1050, 600);
myStage.setScene(myScene);
myStage.show();
}
}
Result:
I had tried to create method and call it from another file to the main class but It won't work the error message said "java.lang.NullPointerException"
Main.class
Keywords kw = new Keywords();
#When("^gmailDD$")
public void gmailDD() throws Throwable{
WebDriverWait wait5s = new WebDriverWait(driver, 5);
String regis = "/html/body/div[2]/div[1]/div[5]/ul[1]/li[3]/a";
String dd = "/html/body/div[1]/div/footer/div/div/div[1]";
String empty = "/html/body/div[1]/div/footer";
kw.clickbyxpath(regis);
String handle= driver.getWindowHandle();
System.out.println(handle);
// Store and Print the name of all the windows open
Set handles = driver.getWindowHandles();
System.out.println("Log window id: "+handles);
driver.switchTo().window("6442450949");
kw.clickbyxpath(empty);
kw.clickbyxpath(dd);
}`
Method.class
WebDriver saddriver;
public void clickbyxpath (String xpathvalue) throws InterruptedException, IOException
{
WebDriverWait sad = new WebDriverWait(saddriver, 10);
//To wait for element visible
System.out.println(xpathvalue);
String x = xpathvalue;
sad.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(x)));
wowdriver.findElement(By.xpath(x)).click();
}
I had tried to do the same coding in the same file, It has no problem but when I move Method.class to the new file, error message said "java.lang.NullPointerException" but I can get "xpathvalue" value.
This Error occur because of it will not able to find your driver instance.
refer below code snippet. this is not cucumber example but you can get idea by this.
Method.class
package testing.framework;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Method {
public WebDriver driver;
WebElement _clickForSearch;
public Method(WebDriver driver) {
this.driver = driver;
}
public Method clickByXpath(String xpathValues) {
WebDriverWait wait = new WebDriverWait(driver, 10);
_clickForSearch = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpathValues)));
_clickForSearch.click();
return this;
}
}
Testing.class
package testing.framework;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Testing {
public static WebDriver driver;
public static void main(String[] args) {
getWebDriver();
String xpathValues= "//div[#class='FPdoLc VlcLAe']//input[#name='btnK']";
Method m1 = new Method(driver);
m1.clickByXpath(xpathValues);
}
public static void getWebDriver() {
System.setProperty("webdriver.chrome.driver", "Your chrome driver path");
driver = new ChromeDriver();
driver.get("https://www.google.com");
}
}
You need to pass your driver instance to another.
So I would suggest you take the webdriver wait out of your method and instantiate it when instantiating your webdriver. I would then create methods like so:
Driver class
private final String USER_DIRECTORY = System.getProperty("user.dir");
private final int GLOBAL_TIMEOUT = 30;
private WebDriver webDriver;
private WebDriverWait webDriverWait;
public Driver(String browserName) {
this.browserName = browserName;
System.out.println(browserName);
switch (this.browserName.toUpperCase()) {
case "CHROME":
initializeChromeDriver();
break;
}
}
private void initializeChromeDriver() {
System.setProperty("webdriver.chrome.driver", USER_DIRECTORY.concat("\\drivers\\chromedriver.exe"));
webDriver = new ChromeDriver();
webDriver.manage().window().maximize();
webDriverWait = new WebDriverWait(webDriver, GLOBAL_TIMEOUT);
}
Click method
public void buttonClickByXpath(String xpath) {
try {
WaitForPreseneOfElement(xpath);
webDriver.findElement(By.xpath(xpath)).click();
} catch (Exception e) {
takeScreenshot();
AllureLog("Failed to click on the button object. Please check your xpath. | xpath used = " + xpath + "");
Assert.fail();
}
}
Test Class
Import your driver class
import Base.Driver;
Then you would need declair your driver class like so:
Driver driver;
Now you will have access to your method using
driver.buttonClickByXpath(//YourXpathHere)
The problem is "Method m1 = new Method(driver);" keyword,
I had coded this line outside the main method.
thank you very much, Sir
How do I simulate a click with coordinates on HtmlPage then get the result a HtmlPage?
I want to click a button without an id or a name
I'm using the library com.gargoylesoftware.htmlunit
not sure about specific system or browser settings, but in general you can do this by following:
import java.awt.event.*;
import java.awt.Robot;
public class test {
int xparam=50;
int yparam=100;
public static void main(String args[]) {
Robot mybot = null;
try {
mybot = new Robot();
} catch (Exception failed) {
System.err.println("Failed instant. Robot: " + failed);
}
int maske = InputEvent.BUTTON1_DOWN_MASK;
mybot.mouseMove(xparam,yparam);
mybot.mousePress(maske);
mybot.mouseRelease(maske);
}
}
For a smoother solution take a look at this ;
No,You can't click button with coordinates(X,Y).
Please specify the element other attributes because it can be click with help of other attribute
I need to capture the full page of IE browser. I am using web driver. Pls help me.
below code is used to capture the present window only.
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));
You can change the browser to full screen before taking the screenshot. This is the code:
private void changeToFullScreen() {
try {
Robot r;
r = new Robot();
r.keyPress(java.awt.event.KeyEvent.VK_F11);
r.keyRelease(java.awt.event.KeyEvent.VK_F11);
driver.sleep(2);
} catch (AWTException e) {
log.error("It was not possible to maximize", e)
driver.manage().window().maximize();
}
}
If you don't want to change the screen size, you can obtain the browser height and take screenShots while you scroll down until the bottom (can be done with Robot):
int numberOfScrolls = pageHeight / browserHeight;
for(int i = 0 ; i < numberOfScrolls ; i++){
takeScreenshot();
scrollDown(browserHeight);
}
concatenateScreenshots();
import java.io.File;
import javax.imageio.ImageIO;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
public class TakeScreenshotWithScroll {
static WebDriver driver;
public static void main(String args[]) throws Exception{
String key = "webdriver.gecko.driver";
String value = "driver/geckodriver.exe";
driver = new FirefoxDriver();
System.setProperty(key, value);
driver.get("ENTER THE URL HERE");
Thread.sleep(2000);
Screenshot fpScreenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(1000)).takeScreenshot(driver);
ImageIO.write(fpScreenshot.getImage(),"PNG",new File("D:///FullPageScreenshot.png"));
}
}
Here is the download link of aShot Jar file