🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# 从一个URL加载一个Document <div><h2>存在问题</h2> <p>你需要从一个网站获取和解析一个HTML文档,并查找其中的相关数据。你可以使用下面解决方法:</p> <h2>解决方法</h2> <p>使用 <code><a title="Creates a new Connection to a URL." href="http://jsoup.org/apidocs/org/jsoup/Jsoup.html#connect%28java.lang.String%29">Jsoup.connect(String url)</a></code>方法:</p> <pre><code>Document doc = Jsoup.connect("http://example.com/").get(); String title = doc.title(); </code></pre> <h2> 说明 </h2> <p><code><a title="Creates a new Connection to a URL." href="http://jsoup.org/apidocs/org/jsoup/Jsoup.html#connect%28java.lang.String%29">connect(String url)</a></code> 方法创建一个新的 <code><a title="A Connection provides a convenient interface to fetch content from the web, and parse them into Documents." href="http://jsoup.org/apidocs/org/jsoup/Connection.html">Connection</a></code>, 和 <code><a href="http://jsoup.org/apidocs/org/jsoup/helper/HttpConnection.html#get%28%29">get()</a></code> 取得和解析一个HTML文件。如果从该URL获取HTML时发生错误,便会抛出 IOException,应适当处理。</p> <p><code><a title="A Connection provides a convenient interface to fetch content from the web, and parse them into Documents." href="http://jsoup.org/apidocs/org/jsoup/Connection.html">Connection</a></code> 接口还提供一个方法链来解决特殊请求,具体如下:</p> <pre><code>Document doc = Jsoup.connect("http://example.com") .data("query", "Java") .userAgent("Mozilla") .cookie("auth", "token") .timeout(3000) .post(); </code></pre> <p>这个方法只支持Web URLs (<code>http</code>和<code>https</code> 协议); 假如你需要从一个文件加载,可以使用 <code><a title="Parse the contents of a file as HTML." href="http://jsoup.org/apidocs/org/jsoup/Jsoup.html#parse%28java.io.File,%20java.lang.String%29">parse(File in, String charsetName)</a></code> 代替。</p><br></div>