如何获取标签a的href属性的确切文本?

问题描述 投票:3回答:2

我使用selenium来获取href属性,lLinks是我的web元素,它具有“href”属性。

String url = lLinks.getAttrbute("href");

如果我的'a'标签的href是<a href='/home'>Home</a>之类的相对路径,则url将返回http://www.domain.com/home

如何让url等于href属性的确切文本?

selenium absolute relative
2个回答
4
投票

我想你不能得到那个“href”。 Selenium仅提供完整路径或相对路径。见下面的代码:

String href = linx.getAttribute("href");
System.out.println("Text is" + href);
String pathName = linx.getAttribute("pathname");
System.out.println("Text is" + pathName);
// Results
// Text is http://www.amazon.com/gp/yourstore/home/ref=nav_cs_ys/180-1519742-0316250
// Text is /gp/yourstore/home/ref=nav_cs_ys/180-1519742-0316250

2
投票

您可以通过阅读整个元素来获取href属性:

lLinks.getAttribute("outerHTML")

这给你了例如:

<a id="button-id" href="#">Click me!</a>

然后你可以使用pattern matching to get the href attribute


0
投票

以下代码将给出确切的href值。

List<WebElement> allLinks = getDriver().findElements(By.tagName("a"));
for (WebElement e : allLinks) {
String html = e.getAttribute("outerHTML");
Pattern p = Pattern.compile("href=\"(.*?)\"");
Matcher m = p.matcher(html);
String relHref = null;
if (m.find()) {
relHref = m.group(1); 
}
System.out.println(relHref);
© www.soinside.com 2019 - 2024. All rights reserved.