简体   繁体   中英

selenium click link href with javascript

I am a newbie to java and selenium. I am having an issue in clicking a link with javascript in href. Below is the page source:

href="javascript:navigateToDiffTab('https://site_url/medications','Are you sure you want to leave this page without saving your changes?');" tabindex="-1">Medications

Please note: I replaced actual url with "site_url" because of business concerns.

I tried below code but it did not work:

driver.findElement(By.cssSelector("a[href^='javascript:navigateToDiffTab'][href$='site_url/medications']")).click();

I do not want to use id or linkText as those changes with different environments and languages.

Any help would be much appreciated.

This part of the selector: href$='site_url/medications' means that href should end with site_url/medications which is not true and this is why you are not getting a match.

How about we simplify it to just "href contains 'medications'":

a[href*=medications]

Use below code. It is working fine for me:-

WebElement element= driver.findElement(By.cssSelector("a[href^='javascript:navigateToDiffTab'][href$='site_url/medications']"))

JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", element);

If the above code will not work for you that means there is a problem with your locator. Then try with some other locator or post some HTML code in your question so we can identify that exact locator for you.

Hope it will help you :)

alexce has already identified the issue with href$='site_url/medications' doing a suffix-match, but it might be helpful to summarise and explain the various CSS attribute selectors you can use.

[attr] Represents an element with an attribute name of attr.

[attr=value] Represents an element with an attribute name of attr and whose value is exactly "value".

[attr~=value] Represents an element with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly "value".

[attr|=value] Represents an element with an attribute name of attr. Its value can be exactly “value” or can begin with “value” immediately followed by “-” (U+002D). It can be used for language subcode matches.

[attr^=value] Represents an element with an attribute name of attr and whose value is prefixed by "value".

[attr$=value] Represents an element with an attribute name of attr and whose value is suffixed by "value".

[attr*=value] Represents an element with an attribute name of attr and whose value contains at least one occurrence of string "value" as substring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM