htmlParse和Jsoup

1、利用htmlParse获取网页信息:

import org.htmlparser.Node;

import  org.htmlparser.NodeFilter;
import  org.htmlparser.Parser;
import  org.htmlparser.filters.TagNameFilter;
import  org.htmlparser.tags.TableTag;
import  org.htmlparser.util.NodeList;

public   class  TestYahoo {
    
public   static   void  testHtml() {
        
try  {
            String sCurrentLine;
            String sTotalString;
            sCurrentLine 
=   "" ;
            sTotalString 
=   "" ;
            java.io.InputStream l_urlStream;
            java.net.URL l_url 
=   new  java.net.URL(
                    
" http://sports.sina.com.cn/iframe/nba/live/ " );
            java.net.HttpURLConnection l_connection 
=  (java.net.HttpURLConnection) l_url
                    .openConnection();
            l_connection.connect();
            l_urlStream 
=  l_connection.getInputStream();
            java.io.BufferedReader l_reader 
=   new  java.io.BufferedReader(
                    
new  java.io.InputStreamReader(l_urlStream));
            
while  ((sCurrentLine  =  l_reader.readLine())  !=   null ) {
                sTotalString 
+=  sCurrentLine;
            }
            System.out.println(sTotalString);

            System.out.println(
" ==================== " );
            String testText 
=  extractText(sTotalString);
            System.out.println(testText);
        } 
catch  (Exception e) {
            e.printStackTrace();
        }

    }

    
/**
     * 抽取纯文本信息
     * 
     * 
@param  inputHtml
     * 
@return
     
*/
    
public   static  String extractText(String inputHtml)  throws  Exception {
        StringBuffer text 
=   new  StringBuffer();

        Parser parser 
=  Parser.createParser( new  String(inputHtml.getBytes(),
                
" 8859_1 " ),  " 8859-1 " );
        
//  遍历所有的节点
        NodeList nodes  =  parser.extractAllNodesThatMatch( new  NodeFilter() {
            
public   boolean  accept(Node node) {
                
return   true ;
            }
        });
        Node node 
=  nodes.elementAt( 0 );
        text.append(
new  String(node.toPlainTextString().getBytes( " 8859_1 " )));
        
return  text.toString();
    }

    
/**
     * 读取文件的方式来分析内容. filePath也可以是一个Url.
     * 
     * 
@param  resource
     *            文件/Url
     
*/
    
public   static   void  test5(String resource)  throws  Exception {
        Parser myParser 
=   new  Parser(resource);

        
//  设置编码
        myParser.setEncoding( " GBK " );
        String filterStr 
=   " table " ;
        NodeFilter filter 
=   new  TagNameFilter(filterStr);
        NodeList nodeList 
=  myParser.extractAllNodesThatMatch(filter);
        TableTag tabletag 
=  (TableTag) nodeList.elementAt( 11 );
            
            System.out.println(tabletag.toHtml());
            
            System.out.println(
" ============== " );

    }

    
/*
     * public static void main(String[] args) { TestYahoo testYahoo = new
     * TestYahoo(); testYahoo.testHtml(); }
     
*/
    
public   static   void  main(String[] args)  throws  Exception {
        test5(
" http://sports.yahoo.com/nba/scoreboard " );
    }

}


2、比htmlparser更好用的html解析工具jsoup,最人性化的地方是,它支持类jquery语法。下载地址:http://jsoup.org/

mport java.util.HashMap;
 2 import java.util.Map;
 3 
 4 import org.jsoup.Jsoup;
 5 import org.jsoup.nodes.Document;
 6 import org.jsoup.select.Elements;
 7 /**
 8  * 
 9  * @author Rocky
10  *
11  */
12 public class spider {
13     private static final String POSTURL="http://59.49.18.116:8008/sxwwpt_wai/inquire/illegalAction!carInquire.action";
14     private void spiderData() throws Exception{
15          Map<String,String> req=new HashMap<String,String>();
16          req.put("authCode", "");
17          req.put("csjcKey","110000");
18          req.put("hpzl", "02");
19          req.put("vioViolation.hphm", "xxx");//您的车牌号
20          req.put("type","1");
21          req.put("pagination.currentPage", "1");
22          req.put("pagination.pageSize", "5");
23          
24          Document doc=Jsoup.connect(POSTURL).data(req).get();
25          Elements newsHeadlines=doc.select(".if_tr td");
26          System.out.println(newsHeadlines.text());
27     }
28     /**
29      * @param args
30      * @throws Exception 
31      */
32     public static void main(String[] args) throws Exception {
33         
34         spider spider=new spider();
35         spider.spiderData();
36     }
37 
38 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java Jsoup是一个用于解析HTML文档的开源库。通过使用Jsoup,您可以轻松地从HTML文档中提取数据或进行数据操作。以下是使用Java Jsoup解析HTML的基本步骤: 1. 下载Jsoup库:您可以从Jsoup的官方网站(https://jsoup.org/)下载Jsoup库的最新版本。 2. 导入Jsoup库:将下载的Jsoup库的JAR文件导入到您的Java项目中。 3. 创建连接:使用Jsoup.connect()方法创建一个Connection对象,将HTML文档的URL作为参数传递给该方法。 4. 获取Document对象:使用Connection对象的get()方法获取一个Document对象,该对象表示整个HTML文档。 5. 使用选择器进行数据提取:使用Jsoup的选择器语法,您可以根据HTML元素的标签、类名、ID等属性来选择和提取数据。 以下是一个基本的Java Jsoup解析HTML的示例代码: ```java import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; public class HtmlParser { public static void main(String[] args) { try { // 创建连接 Connection connection = Jsoup.connect("http://example.com"); // 获取Document对象 Document document = connection.get(); // 使用选择器提取数据 Elements links = document.select("a[href]"); for (Element link : links) { System.out.println("Link: " + link.attr("href")); System.out.println("Text: " + link.text()); } } catch (IOException e) { e.printStackTrace(); } } } ``` 这个示例代码将从"http://example.com"网页中提取所有链接的URL和文本,并打印出来。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

赶路人儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值