I am kinda new to programming and I tried to execute the below code but chrome page is getting loaded but no execution happens and I am facing the below error.
Starting ChromeDriver 72.0.3626.69 (3c16f8a135abc0d4da2dff33804db79b849a7c38) on port 27651
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
Apr 19, 2019 12:23:41 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
My config
windows 10, chrome driver V72 and selenium-3.141.59
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class MyClass {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\ADMIN\\Desktop\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String baseUrl = "http://demo.guru99.com/test/newtours/";
String expectedTitle = "Welcome: Mercury Tours";
String actualTitle = "";
actualTitle = driver.getTitle();
if (actualTitle.contentEquals(expectedTitle)){
System.out.println("Test Passed!");
} else {
System.out.println("Test Failed");
}
driver.close();
}
}
The logs you have posted are not errors. It is the log from the chrome driver.
As it is stated in the log, Detected dialect: OSS log level is INFO. It doesn't prevent your test from running.
The code you have posted should surely print in the console Test Failed.
In your code, you have not gone to the URL you have saved in the baseUrl variable. Before you get the title of the page, you should get the page. Otherwise, it won't give you the desired pages title.
Do the following and your code will load the page and will print Test Passed!
driver.get(baseUrl);
actualTitle = driver.getTitle();
Related
I'm trying to create a program to automate certain downloads, however, when using Selenium-WebDriver, I find I can't seem to find the element needed to log in. I have located the correct element, however actually using the WebDriver#findElement() is giving me issues.
<input id="form-username" class="form-field" form="popup-login" type="text" name="username" value="" tabindex="1" autofocus="">
I've been trying different By methods, however none of them work, along with different ID's, albeit to no avail.
I have checked other posts, but none of them seem to fit as they are just retrieving information from specific points in the HTML like a String, where I want to input information into it.
public void start(String usernameInfo, String passwordInfo) {
driver = new HtmlUnitDriver();
driver.get("https://www.nexusmods.com");
WebElement username = driver.findElement(By.id("form-username"));
username.sendKeys(usernameInfo);
username.submit();
WebElement password = driver.findElement(By.id("form-password"));
password.sendKeys(passwordInfo);
password.submit();
System.out.println(driver.getTitle());
driver.quit();
}
The output log can be viewed here: https://hastebin.com/zuvebosaha.nginx
UPDATE:
Tried ChromeDriver, and found the following code (modified for my use)
public void start(String usernameInfo, String passwordInfo) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\veeay\\Documents\\chromedriver.exe"); //add chrome driver path (System.setProperty("webdriver.chrome.drive",chrome driver path which you downloaded)
WebDriver driver = new ChromeDriver(); // create object of ChromeDriver
driver.manage().window().maximize(); // maximize the browser window
driver.get("https://www.nexusmods.com/"); //enter url
driver.findElement(By.id("form-username")).sendKeys(usernameInfo); //type textbox's id or name or any locater along with data in sendkeys
driver.findElement(By.id("form-password")).sendKeys(passwordInfo);
driver.findElement(By.id("btnLogin")).click();
try {
Thread.sleep(2000); //used thread for hold process
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.quit(); //for close browser
}
resulting in the following: https://hastebin.com/iliyuvucok.cs
UPDATE 2: Oddly enough, now that I actually post the question, I'm doing good. Now I can do everything except select the sign-in button.
public void start(String usernameInfo, String passwordInfo) {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\veeay\\Documents\\chromedriver.exe"); //add chrome driver path (System.setProperty("webdriver.chrome.drive",chrome driver path which you downloaded)
WebDriver driver = new ChromeDriver(); // create object of ChromeDriver
driver.manage().window().maximize(); // maximize the browser window
driver.get("https://www.nexusmods.com/Core/Libs/Common/Widgets/LoginPopUp?url=%2F%2Fwww.nexusmods.com%2F"); //enter url
driver.findElement(By.id("form-username")).sendKeys(usernameInfo); //type textbox's id or name or any locater along with data in sendkeys
driver.findElement(By.id("form-password")).sendKeys(passwordInfo);
driver.findElement(By.id("sign-in-button")).click();
try {
Thread.sleep(2000); //used thread for hold process
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.quit(); //for close browser
}
apparently the sign-in button is not interactable https://hastebin.com/ahuvezoxat.cs
Added explicit wait and it works:
package vee;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Vee {
#Test
public void start() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\pburgr\\Desktop\\selenium-tests\\GCH_driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
// new explicit wait
WebDriverWait webDriverWait = new WebDriverWait(driver, 5);
driver.get("https://www.nexusmods.com/Core/Libs/Common/Widgets/LoginPopUp?url=%2F%2Fwww.nexusmods.com%2F");
// using explicit wait
webDriverWait.until(ExpectedConditions.elementToBeClickable(By.id("sign-in-button")));
driver.findElement(By.id("form-username")).sendKeys("some name");
driver.findElement(By.id("form-password")).sendKeys("some password");
// print true or false by the button state
System.out.println(driver.findElement(By.id("sign-in-button")).isEnabled());
driver.findElement(By.id("sign-in-button")).click();
driver.quit();
}
}
Output:
Starting ChromeDriver 74.0.3729.6 (255758eccf3d244491b8a1317aa76e1ce10d57e9-refs/branch-heads/3729#{#29}) on port 4301
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.
[1560240089.419][WARNING]: This version of ChromeDriver has not been tested with Chrome version 75.
Čer 11, 2019 10:01:31 DOP. org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
true
Maybe when repeating test, recaptcha pops up and disables the button.
commenting out the configuration results in this crash:
thufir#doge:~/NetBeansProjects/selenium$
thufir#doge:~/NetBeansProjects/selenium$ gradle clean fatJar;java -jar build/libs/selenium-all.jar
BUILD SUCCESSFUL in 1m 17s
4 actionable tasks: 4 executed
Jul 09, 2017 3:03:39 PM net.bounceme.dur.web.selenium.Main main
INFO: init..
Jul 09, 2017 3:03:41 PM net.bounceme.dur.web.selenium.Scraper scrape
INFO: {webdriver.gecko.driver=/usr/bin/firefox, url=http://www.google.com, url2=file:///home/thufir/wget/foo.html}
Exception in thread "main" java.lang.IllegalStateException: The path to the driver executable must be set by the webdriver.gecko.driver system property; for more information, see https://github.com/mozilla/geckodriver. The latest version can be downloaded from https://github.com/mozilla/geckodriver/releases
at com.google.common.base.Preconditions.checkState(Preconditions.java:738)
at org.openqa.selenium.remote.service.DriverService.findExecutable(DriverService.java:124)
at org.openqa.selenium.firefox.GeckoDriverService.access$100(GeckoDriverService.java:41)
at org.openqa.selenium.firefox.GeckoDriverService$Builder.findDefaultExecutable(GeckoDriverService.java:115)
at org.openqa.selenium.remote.service.DriverService$Builder.build(DriverService.java:330)
at org.openqa.selenium.firefox.FirefoxDriver.toExecutor(FirefoxDriver.java:207)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:108)
at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:104)
at net.bounceme.dur.web.selenium.Scraper.scrape(Scraper.java:24)
at net.bounceme.dur.web.selenium.Main.run(Main.java:20)
at net.bounceme.dur.web.selenium.Main.main(Main.java:15)
thufir#doge:~/NetBeansProjects/selenium$
thufir#doge:~/NetBeansProjects/selenium$
How or where do I integrate this?
{
"capabilities": {
"alwaysMatch": {
"moz:firefoxOptions": {
"binary": "/usr/local/firefox/bin/firefox",
"args": ["--no-remote"],
"prefs": {
"dom.ipc.processCount": 8
},
"log": {
"level": "trace"
}
}
}
}
}
I don't even know what that means.
code:
package net.bounceme.dur.web.selenium;
import java.util.Properties;
import java.util.logging.Logger;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Scraper {
private static final Logger log = Logger.getLogger(Scraper.class.getName());
public Scraper() {
}
public void scrape(Properties p) {
log.info(p.toString());
String key = "webdriver.gecko.driver";
String url = p.getProperty("url");
String value = p.getProperty(key);
// System.setProperty(key, value);
// System.setProperties(p);
WebDriver driver = new FirefoxDriver();
driver.get(url);
}
}
Preferrably the configuration would be in a properties file. What would the key/value pairs for that properties file?
You can perform the following steps:
Download the latest geckodriver from github.com/mozilla/geckodriver/releases
Check the location of firefox on your machine.
On Mac Firefox is at location: /Applications/Firefox.app/Contents/MacOS/firefox-bin
On Windows Firefox should be at the location: C:\Program Files (x86)\Mozilla Firefox\firefox.exe
Here is the code:
System.setProperty("webdriver.gecko.driver","/Users/monika/Downloads/geckodriver 2"); //the location of geckodriver on your machine
FirefoxOptions options = new FirefoxOptions();
options.setBinary("/Applications/Firefox.app/Contents/MacOS/firefox-bin"); //This is the location where you have installed Firefox on your machine
options.addArguments("--no-remote");
options.addPreference("dom.ipc.processCount",8);
FirefoxDriver driver = new FirefoxDriver(options);
driver.get("http://www.google.com");
I'm trying to Automate a web application selenium 2.0 [webdriver+java].The web application is currently deployed in our UAT servers on our local network.My test cases are executing, but I have to manually enter the Proxy Authentication details for my Chrome instance at the start of the test execution. I have tried all the solutions provided on stack overflow but still, the authentication message pops out.
This is the code I'm using in my driver initializing process
package com.misyn.ess.ui;
import java.util.Arrays;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
/**
*
* #author User
*/
public class DriverClass {
private String baseUrl;
private String driverPath;
private String driverName;
private static WebDriver driver;
private static DriverClass driverClass;
private DriverClass() {
try {
baseUrl = "http://192.168.0.10:8282/ess";
driverPath = "E:\\Work_Folder\\SelTools\\chromedriver.exe";
driverName = "webdriver.chrome.driver";
//Set the location of the ChromeDriver
System.setProperty(driverName, driverPath);
//Create a new desired capability
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
// Create a new proxy object and set the proxy
Proxy proxy = new Proxy();
proxy.setHttpProxy("192.168.0.200:3128");
proxy.setSocksUsername("avishka");
proxy.setSocksPassword("12345678");
//Add the proxy to our capabilities
capabilities.setCapability("proxy", proxy);
//Start a new ChromeDriver using the capabilities object we created and added the proxy to
driver = new ChromeDriver(capabilities);
//Navigation to a url and a look at the traffic logged in fiddler
driver.navigate().to(baseUrl);
// System.setProperty(driverName, driverPath);
// driver = new ChromeDriver();
// driver.get(baseUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Can anyone give me a solution how to give this proxy username and password thing from the application itself than manually entering details on the pop-up(Authentication), any help would be much appreciated.Thanks
the currently answered one is only for
As of Selenium 3.4 it is still in beta
Right now implementation is only done for InternetExplorerDriver
Where I'm using selenium 3.0 and Google Chrome as my web browser.
You can do via MultiPass for HTTP basic authentication
Download the extension from
https://chrome.google.com/webstore/detail/multipass-for-http-basic/enhldmjbphoeibbpdhmjkchohnidgnah
Download the extension as crx. You can get it as crx from chrome-extension-downloader
After that the config is simple.
import java.io.File;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
/**
*
* #author Phystem
*/
public class ChromeAuthTest {
WebDriver driver;
public ChromeAuthTest() {
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
}
private void initDriver() {
ChromeOptions cOptions = new ChromeOptions();
cOptions.addExtensions(new File("MultiPass-for-HTTP-basic-authentication_v.crx"));
driver = new ChromeDriver(cOptions);
configureAuth(
"https://the-internet.herokuapp.com/basic_auth",
"admin",
"admin");
}
private void configureAuth(String url, String username, String password) {
driver.get("chrome-extension://enhldmjbphoeibbpdhmjkchohnidgnah/options.html");
driver.findElement(By.id("url")).sendKeys(url);
driver.findElement(By.id("username")).sendKeys(username);
driver.findElement(By.id("password")).sendKeys(password);
driver.findElement(By.className("credential-form-submit")).click();
}
public void doTest() {
initDriver();
driver.get("https://the-internet.herokuapp.com/basic_auth");
System.out.println(driver.getTitle());
driver.quit();
}
public static void main(String[] args) {
new ChromeAuthTest().doTest();
}
}
I have used a sample site for testing.
Provide your url,username and password in the configure Auth function and try
public class DriverClass {
private String baseUrl;
private String driverPath;
private String driverName;
private static WebDriver driver;
private static DriverClass driverClass;
public DriverClass() {
try {
baseUrl = "http://192.168.0.10:8282/ess";
driverPath = "E:\\Work_Folder\\SelTools\\chromedriver.exe";
driverName = "webdriver.chrome.driver";
System.setProperty(driverName, driverPath);
Proxy proxy = new org.openqa.selenium.Proxy();
proxy.setSslProxy("192.168.0.200" + ":" + 3128);
proxy.setFtpProxy("192.168.0.200" + ":" + 3128);
proxy.setSocksUsername("avishka");
proxy.setSocksPassword("12345678");
DesiredCapabilities desiredCapabilities = DesiredCapabilities.chrome();
desiredCapabilities.setCapability(CapabilityType.PROXY, proxy);
driver = new ChromeDriver(desiredCapabilities);
driver.get(baseUrl);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The proxy setting has been added with desired capabilities to pass values to proxy authentication,worked finally
This code (from Avishka Perera's answer) does not work for me:
proxy.setSocksUsername("avishka");
proxy.setSocksPassword("12345678");
The username and password set in this way do not take effect for the http/https proxy - the Proxy Authentication box still popped up.
I'm using Selenium java 3.141.0, ChromeDriver 2.33 and chrome 70. What works for me is to follow Mike's answer here Selenium using Python: enter/provide http proxy password for firefox .
Create the zip file, then add the extension like this:
ChromeOptions chromeOptions = new ChromeOptions();
chromeOptions.addExtensions(new File("src/test/resources/proxy.zip"));
WebDriver driver = new ChromeDriver(chromeOptions);
One catch is that the above code will run into error if you set "--headless" argument because chrome in headless mode cannot have extension (Is it possible to run Google Chrome in headless mode with extensions?). If your Chrome runs in Docker container and cannot show the UI, then to get this solution work, you'll need to run with Xvfb instead of in headless mode.
Simple method to add authenticated proxy using selenium wire in Both firefox and chrome
In python
Step:1
pip3 install selenium-wire
Step:2
from seleniumwire import webdriver
from selenium import webdriver
step:3
Add proxy in below-mensioned format
proxy= "username:password#ip:port"
options = {'proxy': {'http': proxy, 'https': proxy, 'no_proxy': 'localhost,127.0.0.1,dev_server:8080'}}
step:4
pass proxy as an argument
CHROME
driver = webdriver.Chrome(options=chrome_options, executable_path="path of chrome driver", seleniumwire_options=options)
Firefox
driver = webdriver.Firefox(seleniumwire_options=options, executable_path="path of firefox driver", options=firefox_options)
step:5
Verify proxy applied by requesting the url https://whatismyipaddress.com/
time.sleep(20)
driver.get("https://whatismyipaddress.com/")
Note:
But selenium log shows it runs in without proxy because we are using an external package to apply proxy.
I know this is an old thread, still leaving a solution which worked for me using browsermob proxy, for someone who still needs an option.
Maven dependency:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>net.lightbody.bmp</groupId>
<artifactId>browsermob-core</artifactId>
<version>2.1.5</version>
</dependency>
Java Code:
// I am using firefox
System.setProperty("webdriver.gecko.driver", "C:\\Selenium\\geckodriver.exe");
BrowserMobProxy browsermobProxy = new BrowserMobProxyServer();
browsermobProxy.setChainedProxy(new InetSocketAddress(PROXY_HOSTNAME, PROXY_PORT));
browsermobProxy.chainedProxyAuthorization(PROXY_USERNAME, PROXY_PASSWORD, AuthType.BASIC);
browsermobProxy.start(0);
FirefoxBinary firefoxBinary = new FirefoxBinary();
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setBinary(firefoxBinary );
firefoxOptions.setProfile(firefoxProfile);
firefoxOptions.setProxy(ClientUtil.createSeleniumProxy(browsermobProxy));
WebDriver webDriverWithProxy = new FirefoxDriver(firefoxOptionsWithProxy);
webDriverWithProxy.get("https://stackoverflow.com/");
The approach that worked perfectly fine for me is by using AutoIT.
Install autoIT and prepare a simple script as shown in the picture attached and execute the script file from your testscript using Runtime.getRuntime().exec("\YOUR_SCRIPT.exe") before navigating to the baseURL.
Windows 10 - 32 bit
Selenium Version:
3.0.0 beta 3
Browser:
Firefox 48.02
Eclipse Luna 32 bit
package newpackage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class MyClass {
public static void main(String[] args) {
// declaration and instantiation of objects/variables
System.setProperty "webdriver.firefox.marionette","D:\\Selenium\\geckodriver.exe");
//System.setProperty("webdriver.gecko.driver","D:\\Selenium\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
String baseUrl = "http://newtours.demoaut.com";
String expectedTitle = "Welcome: Mercury Tours";
String actualTitle = "";
// launch Firefox and direct it to the Base URL
driver.get(baseUrl);
// get the actual value of the title
actualTitle = driver.getTitle();
/*
* compare the actual title of the page witht the expected one and print
* the result as "Passed" or "Failed"
*/
if (actualTitle.contentEquals(expectedTitle)){
System.out.println("Test Passed!");
} else {
System.out.println("Test Failed");
}
//close Firefox
driver.close();
// exit the program explicitly
System.exit(0);
}
}
Error:
org.openqa.selenium.firefox.NotConnectedException: Unable to connect
to host 127.0.0.1 on port 7055 after 45000 ms. Firefox console output:
les":[],"targetApplications":[{"id":"{ec8030f7-c20a-464f-9b0e-13a3a9e97384}","minVersion":"1.5","maxVersion":"9.9"}],"targetPlatforms":[],"multiprocessCompatible":false,"signedState":0,"seen":true}
This kind of issues are coming in selenium 3.0 beta version.
If you are using using Selenium Standalone jar then you have to pass marionette as capabilities and initialize FirefoxDriver as follows:
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette", true);
WebDriver driver = new FirefoxDriver(capabilities);
Tried with geckodriver v 0.10.0.
String driverPath = "<path to gecko driver executable>";
public WebDriver driver;
public void launchBrowser() {
System.out.println("launching firefox browser");
System.setProperty("webdriver.gecko.driver", driverPath+"geckodriver.exe");
driver = new FirefoxDriver();
}
EDIT:
To make this whole thing clear, what im trying to do it make the program go to http://www.ultimateprivateservers.com/index.php?a=in&u=IkovPS and click the red "enter and vote" button
What I'm trying to do is access a webpage programmatically and click a href button that goes like this:
Enter and vote
I've looked at a few tuts with htmlUnit and I can't seem to get this working. What am I doing wrong? Could someone point me in the right direction? I'm not very good with java so it will get confusing.
Here is my code:
import com.gargoylesoftware.htmlunit.*;
import com.gargoylesoftware.htmlunit.html.*;
public class HtmlUnitFormExample {
public static void main(String[] args) throws Exception {
WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage("http://www.ultimateprivateservers.com/index.php?a=in&u=IkovPS");
HtmlLink enterAndVoteButton =
page.getElementByName("btn btn-danger");
page=enterAndVoteButton.click();
HtmlDivision resultStatsDiv =
page.getFirstByXPath("//div[#id='vote_message_fail']");
System.out.println(resultStatsDiv.asText());
webClient.closeAllWindows();
}
}
and here is the console log:
SEVERE: IOException when getting content for iframe: url=[http://a.tribalfusion.com/p.media/aPmQ0x0qPp4WYBPGZbE4PJZdodZanVdfb0bQjYrBeXaisRUvDUFB5WHn0mFBoRU7y1T3s5TUj2qfXmEjIYbYgUHBUoP7Cns7uptfG5Evl5teN5ABLpbbL0V7R1VF3XGjNmqJQ3FQ2WFJBW6Q2QEf1ScUMQdUOYtbuTPbx2G32XrnZcVmun4PQgQmnH4HQrXHBAMTAJplZd1Wp/3002246/adTag.html]
org.apache.http.client.ClientProtocolException
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:188)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:72)
at com.gargoylesoftware.htmlunit.HttpWebConnection.getResponse(HttpWebConnection.java:178)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseFromWebConnection(WebClient.java:1313)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponse(WebClient.java:1230)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:338)
at com.gargoylesoftware.htmlunit.html.BaseFrameElement.loadInnerPageIfPossible(BaseFrameElement.java:184)
at com.gargoylesoftware.htmlunit.html.BaseFrameElement.loadInnerPage(BaseFrameElement.java:122)
at com.gargoylesoftware.htmlunit.html.HtmlPage.loadFrames(HtmlPage.java:1993)
at com.gargoylesoftware.htmlunit.html.HtmlPage.initialize(HtmlPage.java:238)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:475)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:342)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:407)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:392)
at HtmlUnitFormExample.main(HtmlUnitFormExample.java:7)
Caused by: org.apache.http.HttpException: Unsupported Content-Coding: none
at org.apache.http.client.protocol.ResponseContentEncoding.process(ResponseContentEncoding.java:98)
at org.apache.http.protocol.ImmutableHttpProcessor.process(ImmutableHttpProcessor.java:139)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:200)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:86)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:108)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:186)
... 14 more
Apr 18, 2015 5:28:37 AM com.gargoylesoftware.htmlunit.IncorrectnessListenerImpl notify
WARNING: Obsolete content type encountered: 'application/x-javascript'.
Exception in thread "main" com.gargoylesoftware.htmlunit.ElementNotFoundException: elementName=[*] attributeName=[name] attributeValue=[btn btn-danger]
at com.gargoylesoftware.htmlunit.html.HtmlPage.getElementByName(HtmlPage.java:1747)
at HtmlUnitFormExample.main(HtmlUnitFormExample.java:10)
Any help is much appreciated.
I took a look at the page and was able to cast a vote using a slightly different method. I prefer to use Selenium (http://www.seleniumhq.org/download/). I was able to use Selenium in Java to successfully cast a vote using the very crude code below. You can edit and optimize this code to your specific needs. I watched the whole process in an Internet Explorer driver but you could also use PhantomJS (http://phantomjs.org/download.html) as your driver if you do not want the window to show. Here is my simple code, the second argument of the setProperty method is the path to your driver executable this will be unique to your computer (you can download the IE driver on the Selenium downloads page as well):
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.Select;
public class SeleniumTest()
{
public static void main(String[] args)
{
try
{
System.setProperty("webdriver.ie.driver"," IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
driver.get("http://www.ultimateprivateservers.com/index.php?a=in&u=IkovPS");
Thread.sleep(3000); //use the wait as shown below
WebElement button = driver.findElement(By.linkText("Enter and vote"));
button.click();
driver.close();
driver.quit();
}catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
A better way to wait for the page to load would be like this:
WebElement button = wait.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Enter and vote")));
You could also find the button using the class like:
WebElement button = wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("btn-danger")));