简体   繁体   English

当有href数据时,li元素的href属性显示为null

[英]href attribute of a li element coming up as null when there is data for the href

I am trying to iterate over a collection of li elements in an ordered list and then print the URL from each element. 我试图遍历一个有序列表中的li元素的集合,然后从每个元素打印URL。

The HTML: HTML:

<div id="global-atoz-navigation">
  <nav role="navigation" aria-label="Suppliers">
    <ol>


          <li class="selected">
            <span class="visuallyhidden">Suppliers starting with </span>
            <strong>A</strong>
          </li>



          <li>
            <span class="visuallyhidden">Suppliers starting with </span>
            <a href="/g-cloud/suppliers?prefix=B">B</a>
          </li>



          <li>
            <span class="visuallyhidden">Suppliers starting with </span>
            <a href="/g-cloud/suppliers?prefix=C">C</a>
          </li>
</ol>
</nav>
</div>

My code so far: 到目前为止,我的代码:

WebElement navDiv = driver.findElement(By.id("global-atoz-navigation"));
List<WebElement> links = navDiv.findElements(By.tagName("li"));
for (WebElement link : links) {
    System.out.println(link.getAttribute("href"));

}

But for some reason this is printing 'null' for each li element. 但是由于某种原因,这为每个li元素打印了“ null”。 Any ideas why? 有什么想法吗?

Your <li> elements don't have an href attribute. 您的<li>元素没有href属性。 The <a> elements inside them do. 其中的<a>元素可以。 Is there a reason you wouldn't do navDiv.findElements(By.tagName("a")) to find those instead? 您是否有理由不选择navDiv.findElements(By.tagName("a"))来查找它们? Or, if there could be anchors you want to avoid, either get all the anchors and filter the bad ones out, or get all the list items and do another li.findElements(By.tagName("a")) on each one. 或者,如果您想避免使用锚,请获取所有锚并过滤出不良锚,或者获取所有列表项并在每个li.findElements(By.tagName("a"))执行另一个li.findElements(By.tagName("a"))

Please note that <li> isn't short for "link". 请注意, <li>不是“链接”的缩写。 It's short for "list item". 这是“列表项”的缩写。

Links are in the "anchor", or <a> , element. 链接位于“ anchor”或<a>元素中。

Referencing from the answer here: 从这里的答案引用:

JSP getAttribute() returning null JSP getAttribute()返回null

"You are not typecasting it to String. request.getAttribute() will return an Object." “您没有将其类型转换为request.getAttribute()将返回一个Object。”

Try using this and see if it works: 尝试使用它,看看是否可行:

String value = (String)link.getAttribute("href");

What's also true is ErikE's answer where you should be grabbing the attributes for the < a > tags not the < li > tags ErikE的回答也是正确的,您应该在其中获取<a>标签而不是<li>标签的属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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