Janus
Janus

Reputation: 309

Select invalid html-tag with Selenium

I am trying to get a WebElement with Selenium:

driver.findElement(By.xpath("//input[@name='j_username']"))

But Selenium says: "Unable to find element with XPath ...". The XPath is valid, I proofed it with FirePath. But the input element has the following invalid code:

<input size="10" type="text" name="j_username" maxlength="8">

I can't change the html-file, despite the fact is there any solution to get the webElement? Thanks in advance!

Upvotes: 1

Views: 1053

Answers (3)

Jamey
Jamey

Reputation: 843

The best solution is to find out what selenium is doing wrong, but without a URL or sample page to test on it's a little hard. Is there anyway you could dump the HTML into a jsfiddle? If there is do that and paste the url into the question and I'm sure someone can find a solution.

If not however, another way to get the results is to do it with jQuery. If firebug is picking it up but not selenium, then there's no reason why jQuery wouldn't get it. Here's how to go about doing that if needed:

Step 1: Is jQuery already present on the page? If so then you don't need to do this bit, otherwise you will need to add it yourself by using driver.executeScript(addjQueryScript) where the script does something like this.

Step 2: call WebElement input = driver.executeScript(elementSelector); where the elementSelector script would be something like \"return $('input[name=\"j_username\"]')\");

My jQuery's not so good, but I believe that should work...

Best of luck!

Upvotes: 0

some_other_guy
some_other_guy

Reputation: 3404

Well I will suggest adding an id to your html code -

<input id="j_username"size="10" type="text" name="j_username" maxlength="8">

and findElement by id -

driver.findElement(By.id("j_username"));

I have faced similar issues with xpath(borwser issues??) but id never fails for me. ;)

By the way I feel your code should be -

driver.findElement(By.xpath(".//*[@name='j_username']"));

Upvotes: 0

eugene.polschikov
eugene.polschikov

Reputation: 7339

try select element with css selector. and also verify in firepath(firebug addon that element is located properly). so your css selector be something like

input[name='j_username']

2nd approach is to use internal firebug mechanism for finding xPaths of elements. See screen attached below enter image description here

After these manipulations driver shoulda handle element properly.

Upvotes: 1

Related Questions