I am a novice in selenium. I want to hit a url, search for all the iframes and in every iframe, I want to inject a Javascript code. So how would I do that. So far, I have come up with basic selenium code but do not know how to inject JS.
public class Poc {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","/home/xxx/xxx/xxx/chromedriver");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://www.sss.org/");
List<WebElement> elements = driver.findElements(By.tagName("iframe"));
for(WebElement element:elements) {
System.out.println(element.getAttribute("id"));
}
driver.close();
System.exit(0);
}
}
To inject code into each iframe you first have to switch to it
import org.openqa.selenium.JavascriptExecutor;
List<WebElement> elements = driver.findElements(By.tagName("iframe"));
for(WebElement element:elements) {
driver.switchTo().defaultContent();
driver.switchTo.frame(element);
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor) driver).executeScript("alert('hello world');");
}
System.out.println(element.getAttribute("id"));
}
Use JavascriptExecutor for writing javascript code in selenium
Example code for you is
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = driver.findElement(By.linkText("Click ME"));
js.executeScript("arguments[0].setAttribute('attr', '10')",element);
Related
I am trying to load web page (https://genpact.taleo.net/careersection/sgy_external_career_section/jobsearch.ftl?lang=en) for scraping using HtmlUnit WebClient. But the content is not being loaded properly. For example, i am unable to find the Apply buttons.
My webclient code is as below
webClient.setCssErrorHandler(new DefaultCssErrorHandler());
webClient.setJavaScriptErrorListener(new DefaultJavaScriptErrorListener());
webClient.setAjaxController(new NicelyResynchronizingAjaxController());
webClient.getCookieManager().setCookiesEnabled(true);
webClient.waitForBackgroundJavaScript(60000);
Can someone please help me with this
This works for me
public static void main(String[] args) throws IOException{
final String url = "https://genpact.taleo.net/careersection/sgy_external_career_section/jobsearch.ftl?lang=en";
try (final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_60)) {
HtmlPage page = webClient.getPage(url);
// waitForBackgroundJavaScript has to be called after every action
// this page is really slow wait for the last part of the dynamic content
while(!page.asText().contains("Previous\r\n1\r\n2\r\n3\r\n4\r\n")) {
webClient.waitForBackgroundJavaScript(1_000);
}
System.out.println("-------------------------------------------------------------------------------");
System.out.println(page.asText());
System.out.println("-------------------------------------------------------------------------------");
}
}
there has been an automation side project I've been working on in my spare time and I've been trying to incorporate JavascriptExecutor into my Page Object Model since some of the portions of the website I picked isn't functioning when clicking on tag.
Currently this is how I my code set up in the PageObject class (my superclass for my Page-Object Model):
public class PageObject {
protected Driver driver;
public Actions act;
public JavascriptExecutor js = (JavascriptExecutor) this.driver;
PageObject(Driver driver){
this.driver = driver;
PageFactory.initElements(driver, this);
this.act = new Actions(driver);
}
}
This is the layout for the Driver class (which implements the WebDriver):
public class Driver implements WebDriver {
public WebDriver driver;
String browserName;
public JavascriptExecutor js;
public Driver(String browserName) {
this.browserName = browserName;
if (browserName.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", "./resources/webdrivers/chromedriver_win32/chromedriver.exe");
this.driver = new ChromeDriver();
this.js = (JavascriptExecutor) this.driver;
}
// Below are other if conditions for different browsers.
Currently, I'm getting a NullpointerException with js, but I know if I initialize js inside the PageObject constructor, I get hit with a ClassCastException. (I have these classes set up in a Maven Project.)
I've looked around online and this doesn't appear to be a common topic that gets asked and right now, I'm completely stumped on how to solve this or if it's even possible. Has anyone else encountered this situation?
Update: figured out the problem.
public class PageObject {
protected Driver driver;
public Actions act;
PageObject(Driver driver){
this.driver = driver;
PageFactory.initElements(driver, this);
this.act = new Actions(driver);
}
}
public class Driver implements WebDriver {
public WebDriver driver;
String browserName;
public static JavascriptExecutor js;
public Driver(String browserName) {
this.browserName = browserName;
if (browserName.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", "./resources/webdrivers/chromedriver_win32/chromedriver.exe");
this.driver = new ChromeDriver();
js = (JavascriptExecutor) this.driver;
}
// Below are other if conditions for different browsers.
I had to change js into static and then wherever I have a portion of the website where the are non-clickable, I call on Driver.js to execute whatever command I need for any webpage my framework tests.
I am using selenium webdriver to automate a web page. My selenium code is not identifying the link. I am getting the following error.
Exception in thread "main" org.openqa.selenium.NoSuchElementException:
no such element: Unable to locate element:
{"method":"xpath","selector":"/html/body/font/font/b/a[2]"} (Session
info: chrome=44.0.2403.89)
This is the code i am using .
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver","C:\\Program Files (x86)\\Google\\Chrome\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("url");
driver.findElement(By.xpath("/html/body/font/font/b/a[2]")).click();
}
Thanks in advance
If you are getting NoSuchElementException as your provided exception, There are may be following reasons :-
May you are locating with incorrect xpath, So you need to share HTML for better locator solution.
May be when you are going to find element, it would not be present on the DOM, So you should implement WebDriverWait to wait until element visible and clickable as below :-
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement el = wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Duty Office")));
el.click();
May be this element is inside any frame or iframe. If it is, you need to switch that frame or iframe before finding the element as below :-
WebDriverWait wait = new WebDriverWait(driver, 10);
//Find frame or iframe and switch
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt("your frame id or name"));
//Now find the element
WebElement el = wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Duty Office")));
el.click();
//Once all your stuff done with this frame need to switch back to default
driver.switchTo().defaultContent();
Hope it helps...:)
There are two possible situation
1) you might type wrong url
2) your expected element xpath is wrong.
please validate your xpath with
this tolol : https://chrome.google.com/webstore/detail/xpath-helper/hgimnogjllphhhkhlmebbmlgjoejdpjl?hl=en
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\Program Files (x86)\Google\Chrome\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("Valid url");
driver.findElement(By.xpath("your valid XPATH")).click();
driver.close();
}
I am working on a task in which we need to put one of our HTML & JS based project inside a JavaFX project or any other suitable containers which are out there. The purpose is to create an app, which can directly be deployed and would prevent any users from checking out the source code of HTML & JS.
Some time back when I was checking out JavaFX, I read that it supports JS, and JS can be used with it. Is there any way to create a container inside which I can put my HTML&JS files by giving path, etc?
How can I go about this? Whatever I am trying to do, what is it called. Any help, pointers, suggestions, would be nice.
Initial test
public class Main extends Application {
private Scene scene;
MyBrowser myBrowser;
#Override
public void start(Stage primaryStage) throws Exception{
primaryStage.setTitle("Test web");
myBrowser = new MyBrowser();
scene = new Scene(myBrowser, 1920, 1200);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
class MyBrowser extends Region {
final String hellohtml = "hello.html";
WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
public MyBrowser(){
URL urlHello = getClass().getResource("hello.html");
webEngine.load(urlHello.toExternalForm());
getChildren().add(webView);
}
}
As #sillyfly suggested use a WebView:
File f = new File(..);
// ..
final WebView webview = new WebView();
webview.getEngine().load(f.toURI().toURL().toString());
The hard part for me is always to figure out the right location to be used to reference the file.
Another option is when you have the HTML in the form of a string to load that as content:
String html = ...
webview.getEngine().loadcontent(html)
Be sure to check out at least the JavaDoc on WebView and WebEngine`
I want to load contents of below web page in console application using c#.
http://justicecourts.maricopa.gov/findacase/casehistory.aspx
Using below code I am getting empty on the screen but it works perfectly if I load google.com web page.
By using WebClient and WebRequest I was getting error "Please enable javascript" and content was not loading so I used below code and javascipt error is not displaying now but web page content is not loading. I am struggling with this issue quite from long time, have seen lot of post regarding this and couldn't get this work.
Could anyone please help?
Thanks in Advance..
class Program
{
private static bool completed = false;
private static WebBrowser wb;
[STAThread]
static void Main(string[] args)
{
wb = new WebBrowser();
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
wb.Navigate("http://justicecourts.maricopa.gov/findacase/casehistory.aspx");
while (!completed)
{
Application.DoEvents();
Thread.Sleep(100);
}
Console.Write("\n\nDone with it!\n\n");
Console.ReadLine();
}
static void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
Console.WriteLine(wb.Document.Body.InnerHtml);
completed = true;
}
}
If you literally just want to dump the contents of that URL out to the console, try this:
using(WebClient client = new WebClient()) {
Console.WriteLine(client.DownloadString(url));
}
try adding more wait.
static void Main(string[] args)
{
wb = new WebBrowser();
wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
wb.Navigate("http://justicecourts.maricopa.gov/findacase/casehistory.aspx");
while (!completed)
{
Application.DoEvents();
Thread.Sleep(100);
}
//wait even more
for (int i = 0; i < 6; i++)
{
Application.DoEvents();
Thread.Sleep(1000);
}
Console.Write("\n\nDone with it!\n\n");
Console.ReadLine();
}
otherwise you can use EO Browser it is paid. but in your case trail will work cause it is not GUI application.as it shows trail message in GUI.
in EO you can say..
EOContorol.WebView.LoadUrlAndWait(URL);
Try using PhantomJs
basicaly like running a webbrowser without a window. (headless)