Load a Document from a URL(从一个url中加载文档)

Problem(解决)
You need to fetch and parse a HTML document from the web(你需要从一个url地址获得并解析html文档), and find data within it (并在里面搜索数据)(screen scraping抓取数据).

Solution(解决)
Use the Jsoup.connect(String url) method(使用这个Jsoup.connect(String url)方法):

Document doc = Jsoup.connect("http://example.com/").get();
String title = doc.title();

Description
The connect(String url) method creates a new Connection(这个connect(String url)方法创建一个新的连接), and get() fetches and parses a HTML file(并使用get()获得和解析一个HTML文件). If an error occurs whilst fetching the URL(如果抓取的URL地址出现错误), it will throw an IOException(它会抛出IOException错误), which you should handle appropriately(你应该用合适的方法处理他).

The Connection interface is designed for method chaining to build specific requests(用连接设计方法,来构建特定请求):

Document doc = Jsoup.connect("http://example.com")
  .data("query", "Java")
  .userAgent("Mozilla")
  .cookie("auth", "token")
  .timeout(3000)
  .post();

This method only su ports web URLs (这种方法只能使用web url)(http and https protocols); if you need to load from a file(如果你需要加载一个文件), use the parse(File in, String charsetName) method instead(可以用parse(File in, String charsetName)这个方法代替).

猜你喜欢

转载自liuzejian4.iteye.com/blog/1634388