selenium 点击 link href with javascript

selenium click link href with javascript

我是 java 和 selenium 的新手。我在 href 中单击带有 java 脚本的 link 时遇到问题。 以下是网页来源:

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

请注意:出于业务考虑,我将实际 url 替换为 "site_url"。

我试过下面的代码,但没有用:

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

我不想使用 id 或 linkText,因为它们会随着环境和语言的不同而变化。

如有任何帮助,我们将不胜感激。

选择器的这一部分:href$='site_url/medications' 意味着 href 应该以 site_url/medications 结尾,这是不正确的,这就是你没有得到匹配的原因。

我们如何将其简化为 "href contains 'medications'":

a[href*=medications]

使用下面的代码。它对我来说很好用:-

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

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

如果以上代码对您不起作用,则说明您的定位器有问题。然后在您的问题中尝试使用其他定位器或 post 一些 HTML 代码,以便我们可以为您确定确切的定位器。

希望对您有所帮助:)

alexce 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 你可以用。

[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.