Jsoup后台解析html、jsp网页
2016-09-29 09:38
375 查看
在一些网络爬虫或者从第三方网站抓取信息的程序都面临1个问题,如何从网页中把所需的信息提取出来,Jsoup是个比较好的选择,它能把网站内容解析成Document,再从document中取element就是个简单的事了。这里介绍1下Jsoup的基本用法。
首先需要下载jar包,jsoup-1.9.2.jar
首先需要下载jar包,jsoup-1.9.2.jar
1、Jsoup解析字符串
public void parseString() { String html = "<html><head><script type=\"text/javascript\">var date = new Date();alert(date);function sub(u){var token = document.getElementById(\"token\").value;var durl = u + \"token=\" + encodeURIComponent(token);window.open(durl);}</script></head><body><br/><br/>token:<input type=\"text\" name=\"token\" id=\"token\" style=\"width:500\" value=\"uGyUoJ8A6+ETMgIVYAHTpt/l/cY=\"/></input> <br/><br/><input class='butt' type=\"button\" value=\"打开本地\" name=\"sub\" onclick=\"sub('http://localhost:8080/mapbar-fieldwork/setting/setting!index.action?')\" style=\"left:200\"></input><input type=\"button\" value=\"打开44\" name=\"sub\" onclick=\"sub('http://10.30.20.44:8181/mapbar-fieldwork/setting/setting!index.action?')\" style=\"left:200\"></input><input type=\"button\" value=\"获取权限接口\" name=\"sub\" onclick=\"sub('http://localhost:8080/mapbar-fieldwork/newaccount/newaccount!queryUserPermissions.action?projectId=666&')\" style=\"left:200\"></input><input type=\"button\" value=\"获取权限接口\" name=\"sub\" onclick=\"sub('http://localhost:8080/mapbar-fieldwork/newaccount/newaccount!queryProjectPermissions.action?projectId=666&')\" style=\"left:200\"></input></body></html>"; //Jsoup解析html Document doc =Jsoup.parse(html,"utf-8"); //根据id获取元素 Element e1 = doc.getElementById("token"); //根据属性获取元素s Elements e2s = doc.getElementsByAttribute("onclick"); //根据属性+属性值 Elements e3s = doc.getElementsByAttributeValue("type", "text"); //根据class Elements e4s = doc.getElementsByClass("butt"); //根据 标签 Elements e5s = doc.getElementsByTag("head"); Elements e6s = doc.select("input[type]"); p(e6s); }
2、Jsoup解析url
Jsoup可以直接解析1个网址,把网站的返回内容解析出来public void parseUrl() { try { URL url = new URL("http://www.baidu.com"); Document doc = Jsoup.parse(url, 1000); Elements e1s = doc.select("a[href=http://news.baidu.com]"); p(e1s); } catch (IOException e) { e.printStackTrace(); } }
3、Jsoup解析本地文件
可以把html文件解析出来public void parseFile() { File file = new File("C:/Users/Administrator/Desktop/测试页面.html"); try { Document doc = Jsoup.parse(file, "GBK"); p(doc); } catch (IOException e) { e.printStackTrace(); } }
public static void p(Object o) { System.out.println(o); }
相关文章推荐
- 使用Jsoup解析html网页
- Java网页资源抓取例子(使用第三方包Jsoup解析Html)
- 使用Jsoup解析html网页
- 使用Jsoup解析html网页
- SpringMvc出现Jsp页面不能正常解析成html网页
- 安卓新闻客户端(二) JSOUP解析HTML 抓取网页内容
- jsoup 解析html网页标签获取数据(java 网页解析 数据)
- 【转载】使用Jsoup解析html网页
- 使用Jsoup解析html网页
- 使用Jsoup解析html网页
- JSoup——用Java解析html网页内容
- 网页语言有html,php.jsp,无论什么语言浏览器总是能正常显示,这个解析工作是浏览器完成的吗?
- Jsoup 解析Html网页
- 使用Jsoup解析html网页
- 使用Jsoup解析Html,获取网页内容
- 【Java Utility】Jsoup网页爬虫工具--解析HTML语句片段【四】
- 使用了开源的jsoup进行解析html
- Python写爬虫——抓取网页并解析HTML
- Java抓取网页 解析网页HtmlParser
- 用jsp设计网页的时候如何跟后台数据库相连