Jsoup后台解析html、jsp网页

在一些网络爬虫或者从第三方网站抓取信息的程序都面临1个问题,如何从网页中把所需的信息提取出来,Jsoup是个比较好的选择,它能把网站内容解析成Document,再从document中取element就是个简单的事了。这里介绍1下Jsoup的基本用法。

首先需要下载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\" οnclick=\"sub('http://localhost:8080/mapbar-fieldwork/setting/setting!index.action?')\" style=\"left:200\"></input><input type=\"button\" value=\"打开44\" name=\"sub\" οnclick=\"sub('http://10.30.20.44:8181/mapbar-fieldwork/setting/setting!index.action?')\" style=\"left:200\"></input><input type=\"button\" value=\"获取权限接口\" name=\"sub\" οnclick=\"sub('http://localhost:8080/mapbar-fieldwork/newaccount/newaccount!queryUserPermissions.action?projectId=666&')\" style=\"left:200\"></input><input type=\"button\" value=\"获取权限接口\" name=\"sub\" οnclick=\"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);
	}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值