jsoup获取href的内容

u4dcyp6a  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(384)

我正在使用jsoup开发一个web scraper,希望从表中拉出一个链接。
这就是我所看到的:

  1. <ul class="inline-list indent>
  2. <li>
  3. ::marker
  4. <a href="www.linkhere.com" title="Some Text">Some Other Text</a>
  5. (Date & Time Stamp)
  6. </li>

我想要www.linkhere.com 还有一些其他的文字。我已经想好了如何获取其他文本,但我无法获取www.linkhere.com.
这就是我所尝试的:

  1. Document results = Jsoup.connect(url).get();
  2. tTable = ("li:nth-of-type(1)");
  3. Element row : results.select("ul.indent.inline-list:nth-of-type(1)")
  4. Element link = results.select("ul.indent.inline-list:nth-of-type(1) > a").first();
  5. tName = row.select(tTable).text();
  6. articleLink = link.attr("href");
  7. System.out.println(tName);
  8. System.out.println(articleLink);

这给了我一个错误:
nullpointerexception:无法调用“org.jsoup.nodes.element.attr(string)”,因为“llink”为null

xj3cbfub

xj3cbfub1#

您正在使用这样的选择器:

  1. "ul.indent.inline-list:nth-of-type(1) > a"

第一部分 ul.indent.inline-list:nth-of-type(1) 选择第一个 <ul> 元素。第二部分 > a 希望如此 <a> 将是 <ul> . 这和你想要的不符,因为 <li> 因此解决方案是使用:

  1. "ul.indent.inline-list:nth-of-type(1) > li > a"

或者你的想法是和第一个相匹配 <li> 您必须使用:

  1. "ul.indent.inline-list > li:nth-of-type(1) > a"

相关问题