简体   繁体   English

Jsoup-如何选择目标元素下面的元素?

[英]Jsoup - How to select the element below target element?

I have a list of .span6>h6 elements that may or may not exist depending on if a user has filled out that option on their profile page. 我有一个.span6>h6元素列表, .span6>h6元素可能存在或不存在,这取决于用户是否在个人资料页面上填写了该选项。 I want to get the value of each of these options (if they exist). 我想获取每个选项的值(如果存在)。

The value of these options is stored inside each of the .span6>h6 elements as a <pre> tag. 这些选项的值作为<pre>标记存储在每个.span6>h6元素内。 I need to get each one of the h6 elements, read its contents and for each option store the value which is contained in the element below it, in the correct place. 我需要获取h6元素中的每个元素,读取其内容,并为每个选项将包含在其下面的元素中的值存储在正确的位置。

Here is an example of what I am trying to do. 这是我正在尝试做的一个例子。

<div class="row">
  <div class="span6">
    <h6>Gender</h6>
    <pre>Male</pre>
  </div>
  <div class="span6">
    <h6>Location</h6>
    <pre>Someplace</pre>
  </div>
  <div class="span6">
    <h6>Occupation</h6>
    <pre>Figuring out this problem</pre>
  </div>
  <div class="span6">
    <h6>Interests</h6>
    <pre>Figuring out this problem</pre>
  </div>
</div>

Another in depth example, in case my first one was confusing. 另一个深度示例,以防万一我的第一个令人困惑。 If the h6 element exists with the contents "Gender", get the next element <pre> and store the text Male somewhere. 如果h6元素的内容为“性别”,则获取下一个元素<pre>并将文本“男”存储在某处。

Any help would be appreciated, thanks in advance! 任何帮助将不胜感激,在此先感谢!

I did not test it, but I think the following can work: 我没有对其进行测试,但是我认为以下可以工作:

Elements els = Jsoup.parse(html).select( ".span > h6" );
for (Element el : els) {
        String option = el.text();
        String value = el.nextElementSibling().text();
}

.nextElementSibling() will get the first element after your h6 ; .nextElementSibling()将获取h6之后的第一个元素; if you think you'll need to be specific and get only pre siblings, you can replace that line with the following: 如果你认为你需要是具体的,只能得到pre兄弟姐妹,你可以替换下面一行:

String value = el.siblingElements().select( "pre" ).first().text();

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

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