繁体   English   中英

用JSoup解析HTML

[英]Html parsing with JSoup

我正在尝试解析以下URL的html:

http://ocw.mit.edu/courses/aeronautics-and-astronautics/16-050-thermal-energy-fall-2002/

获得“ <p>”标签的文本,其中包含讲师的姓名。 所需的信息位于“ <p>”标签内,但是我无法使用JSoup检索标签。 我不知道我在做什么错,因为当我将标记保存在Element对象中时,将其称为“ b”,然后调用b.getAllElements(),它不会显示

作为要素之一。 这不是Jsoup的getAllElements()方法做什么吗? 如果不能,请向我解释我显然缺少的层次结构,因为解析器无法找到

标签,其中包含我需要的文本,在这种情况下为“ Prof. Zoltan Spakovszky”。

任何帮助将不胜感激。

public void getHomePageLinks()
{
    String html = "http://ocw.mit.edu/courses/aeronautics-and-astronautics/16-050-thermal-energy-fall-2002/";
    org.jsoup.nodes.Document doc = Jsoup.parse(html);

    Elements bodies = doc.select("body");

    for(Element body : bodies )
    {
        System.out.println(body.getAllElements());
    }

}

输出为:

http://ocw.mit.edu/courses/aeronautics-and-astronautics/16-050-thermal-energy-fall-2002/

是否应该打印出文档中body标签内的所有元素?

我对JSoup一无所知,但是似乎如果您想使用讲师​​的姓名,则可以使用以下方法进行访问:

Element instructor = doc.select("div.chpstaff div p");

也许你已经解决了,但我已经努力了,所以无法抗拒提交

import java.io.IOException;
import java.util.logging.*;
import org.jsoup.*;
import org.jsoup.nodes.*;
import org.jsoup.select.*;
public class JavaApplication17 {

public static void main(String[] args) {

try {
   String url = "http://ocw.mit.edu/courses/aeronautics-and-astronautics/16-050-thermal-energy-   fall-2002/";
  Document doc = Jsoup.connect(url).get();
  Elements paragraphs = doc.select("p");
  for(Element p : paragraphs)
    System.out.println(p.text());

} 
catch (IOException ex) {
  Logger.getLogger(JavaApplication17.class.getName())
        .log(Level.SEVERE, null, ex);
   }
  }
}

is it what u meant?

这是一个简短的示例:

// Connect to the website and parse it into a document
Document doc = Jsoup.connect("http://ocw.mit.edu/courses/aeronautics-and-astronautics/16-050-thermal-energy-fall-2002/").get();

// Select all elements you need (se below for documentation)
Elements elements = doc.select("div[class=chpstaff] p");

// Get the text of the first element
String instructor = elements.first().text();

// eg. print the result
System.out.println(instructor);

在这里查看jsoup选择器api的文档: Jsoup Codebook
它不是很难使用,但功能非常强大。

这是一个代码

Document document = Jsoup.connect("http://ocw.mit.edu/courses/aeronautics-and-astronautics/16-050-thermal-energy-fall-2002/").get();

        Elements elements = document.select("p");
        System.out.println(elements.html());

您可以使用Jsoup的Selector属性选择所有标签。 它将返回文本和标签

        Elements ele=doc.select("p");
      ' String text=ele.text();
        System.out.println(text);

试试这个,我认为它会起作用

暂无
暂无

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

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