2015-04-01 84 views
2

我是新来的CSS,并尝试通过Java的Jsoup解析器解析HTML。CSS选择器“合并”元素

示例HTML:

<p>However much beautiful the s6 Edge looks, I doubt [...] the <a title="Samsung Unveils the Galaxy Note 4 and curved screen Note Edge" href="http://www.example.com/">Note Edge</a>, the dual gently curved screen [...] or accidental palm taps.</p> 

我已经得到了<p>元素中的文字如下:

Elements text = doc.select("p"); 

     for (Element element : text) { 
      System.out.println(element.ownText() + "\n"); 
     } 

输出:

但是很多漂亮S6边缘看起来,我怀疑[...],双重 轻轻弯曲的屏幕或偶然的手掌水龙头。

人们可以看到,文Note Edge insde的<a>元素没有显示出来。

所以我想问是否有任何方法可行,显示整个文本,包括<a>元素中的文字如下:

但是很多漂亮S6的边缘看起来,我怀疑[... ] 注边, 双轻轻弯曲的屏幕或偶然手掌水龙头。

我很满意每一个建议!

回答

1

docsownText()

获取仅此元素所拥有的文本; 没有得到所有孩子的合并文本。

想要调用element.text(),而是想要包含子节点的内容。

+0

先生,你应该有一个奖牌的子节点。谢谢!! – user944351 2015-04-01 15:08:33

1

做这样的:

for (Element element : text) { 
    System.out.println(element.text() + "\n"); 
} 

您应该使用text()而不是ownText(),为ownText()得到任何子元素的文本。

+0

谢谢,现在就完成! – user944351 2015-04-01 15:09:19

0

你可以做的是,代替文本是纯文本,然后是<a></a>标签,然后更纯文本,你可以包装文本,然后获得<p></p>元素的每个子元素的文本。

<p id="myParagraph"> 
 
    <span>However much beautiful the s6 Edge looks, I doubt [...] the </span> 
 
    <a title="Samsung Unveils the Galaxy Note 4 and curved screen Note Edge" href="http://www.example.com/">Note Edge</a> 
 
    <span>, the dual 
 
     gently curved screen [...] or accidental palm taps.</span> 
 
</p>

所以,你的函数将遍历元素<p>

//I don't known jsoup so i use javascript directly 
    var childrens= document.getElementByID("myParagraph").children; 
     childrens.forEach(function(child) { 
      console.log(child.textContent() + "\n"); 
     }); 
+0

谢谢,但用text()方法,标签不再可见..所以前两个家伙的解决方案正在为我工​​作。 – user944351 2015-04-01 16:23:00