Bill Ray Bill Ray - 18 days ago 8
Java Question

Selenium HtmlUnitDriver Login to Website

I am trying to use an HtmlUnitDriver to login to marketwatch.com. I don't think the program is ever getting past the login prompt, and I did check that I have the correct email and password...

Thank you so much for trying to help me!

Here's my commented code:

static Logger log = Logger.getLogger("com.gargoylesoftware");
public static void main(String[] args) throws InterruptedException {
log.setLevel(Level.OFF);
// Create a new instance of the html unit driver
WebDriver driver = new HtmlUnitDriver();
// Go to marketwatch
driver.get("http://www.marketwatch.com/game/");
System.out.println(driver.getTitle()); // prints 'Virtual Stock Exchange Games (VSE) - MarketWatch.com'
// Click on 'login'
WebElement login = driver.findElement(By.id("profilelogin"));
login.click();
System.out.println(driver.getTitle()); // prints 'Log In'
// Enter username and password
WebElement email = driver.findElement(By.id("username"));
email.sendKeys(Ref.EMAIL);
WebElement pass = driver.findElement(By.id("password"));
pass.sendKeys(Ref.PASSWORD);
// Click submit button
WebElement submit = driver.findElement(By.id("submitButton"));
submit.click();
System.out.println(driver.getTitle()); // prints 'Log In' (same title as before we tried to log in)
// Try to find
WebElement game = driver.findElement(By.xpath("//*[@id='maincontent']/section[1]/table/tbody/tr[1]/td[1]/a"));
// This gets printed to console:
// Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate a node using //*[@id='maincontent']/section[1]/table/tbody/tr[1]/td[1]/a
// I don't think it's ever getting past the login screen...
// You don't really have to read past this, unless you think I might've messed something else up and you want to fix it.
game.click();
WebElement trade = driver.findElement(By.xpath("//*[@id='vse-nav']/ul/li[2]/a"));
trade.click();
WebElement searchBar = driver.findElement(By.className("instrumentsearch ac_input unused"));
searchBar.sendKeys("GOOG");
searchBar.submit();
System.out.println(driver.getTitle());

driver.quit();
}

Answer

Try to enable javascript, the website needs it:

    // Create a new instance of the html unit driver
    WebDriver driver = new HtmlUnitDriver(true);

You can enable JavaScript by doing this way as well:

    driver.setJavascriptEnabled(true);