用java读取百度新闻页面(http://news.baidu.com)右边前10个新闻热搜词,废话不多说,附上代码和截图

速度比较慢,因为没做任何的优化,甚至里面的字符串的循环连接都是用的“+”号,有时间再改进吧

import java.net.*; import java.awt.*; import java.awt.event.*; import java.io.*; import javax.swing.*; public class Win{ public static void main(String[] args){ Get get = new Get(); get.getInfo(); W w = new W(get.getTitle(),get.getUrl()); w.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } } class W extends JFrame{ String[] newsTitle; String[] newsUrl; JButton jbtn; W(String[] title,String[] url){ newsTitle = title; newsUrl = url; setTitle("TOP10百度热搜关键词(Ver 1.0)"); setBounds(150,150,320,350); setBackground(new Color(212,208,200)); Panel panel = new Panel(); EventDo eventDo = new EventDo(this); panel.setLayout(new GridLayout(10,1)); for(int i = 0;i < 10;i++){ ButtonEx btn = new ButtonEx(newsTitle[i]); btn.addActionListener(eventDo); btn.setUrl(newsUrl[i]); panel.add(btn); } add(panel,BorderLayout.NORTH); Panel panel2 = new Panel(); jbtn = new JButton("点击进入我的CSDN Blog :)"); jbtn.addActionListener(eventDo); panel2.add(jbtn); add(panel2,BorderLayout.SOUTH); setVisible(true); setResizable(false); } } class EventDo implements ActionListener{ W w; Desktop desktop; EventDo(W w){ this.w = w; desktop = Desktop.getDesktop(); } public void actionPerformed(ActionEvent e){ if(w.jbtn == e.getSource()){ try{ desktop.browse(new URI("http://blog.csdn.net/qingchuninfo")); }catch(Exception ex){ ex.printStackTrace(); } }else{ try{ desktop.browse(new URI(((ButtonEx)e.getSource()).getUrl())); }catch(Exception ex){ ex.printStackTrace(); } } } } //获取新闻类返回两个数组 class Get{ String url = "http://news.baidu.com"; URL u; BufferedReader in; String content; String news; String[] title = new String[10]; String[] Url = new String[10]; public void getInfo(){ try{ u = new URL(url); in = new BufferedReader(new InputStreamReader(u.openStream())); String s; while((s = in.readLine()) != null){ content += s; } in.close(); }catch(Exception e){ e.printStackTrace(); } news = content.substring(content.indexOf("<dd class=\"hotwordstop\">"),content.indexOf("<div class=\"hotworddiv02 hotwords_cont\">")); for(int i = 0;i < 10;i++){ int startIndex = news.indexOf("<a href=\"http://news.baidu.com/"); int endIndex = news.indexOf("</a>"); int endUrl = news.indexOf("target=",startIndex); Url[i] = news.substring(startIndex+9,endUrl-2); int startTitle = news.indexOf("\">",endUrl); title[i] = news.substring(startTitle+2,endIndex); news = news.substring(endIndex+4); } } public String[] getTitle(){ return title; } public String[] getUrl(){ return Url; } } class ButtonEx extends JButton{ ButtonEx(String title){ super(title); } private String url; public void setUrl(String url){ this.url = url; } public String getUrl(){ return url; } }
java桌面程序读取百度热搜的前10个关键字新闻

分类:

技术点:

相关文章: