1. 程式人生 > >java-爬取手機高清桌布

java-爬取手機高清桌布


public class DownWallpaper extends JFrame implements ActionListener{ private JButton down = null; public DownWallpaper(){ down = new JButton("下載手機桌布"); down.setFont(new Font("微軟雅黑",Font.ITALIC,20)); down.addActionListener(this); this.setResizable(false); this.add(down); this.setTitle("高清桌布下載"); this.setSize(250, 150); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setLocationRelativeTo(null); this.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource()==down) { try { JOptionPane.showMessageDialog(this, "正在下載請勿關閉主窗體!"); JOptionPane.showMessageDialog(this, "詳細資訊請檢視:https://sj.enterdesk.com/"); JOptionPane.showMessageDialog(this, "下載完成後請到:d:/img下檢視"); load("https://sj.enterdesk.com/"); } catch (Exception e1) { e1.printStackTrace(); } } } public static void main(String[] args) { new DownWallpaper(); } /** * 載入連結 * @param urls * @throws Exception */ public static void load(String urls) throws Exception{ Connection connect = Jsoup.connect(urls); Document document = connect.get(); Elements links = document.getElementsByTag("img"); //迴圈爬取圖片 for(Element link : links){ String url = link.attr("src");//下載的url String endWith = url.substring(url.lastIndexOf("."));//檔案字尾名 String fileName = link.absUrl("alt").substring(link.absUrl("alt").lastIndexOf("/"));//檔名 download(url,endWith,fileName); } //獲取所有的<li> Elements select = document.select("a"); Elements addClass = select.addClass("next_p"); for (Element element : addClass) { if (element.text().equals("下一頁")) { //獲取超連結 String attr = element.attr("href"); //遞迴迴圈下載 load(attr); }else{ continue; } } } /** * 下載圖片 * @param url */ public static void download(String url,String endWith,String fileName) throws Exception{ File file = new File("d:/img/"); if (!file.exists()){ file.mkdir(); }else{ file.delete(); file.mkdir(); } URL url2 = new URL(url); InputStream is = url2.openConnection().getInputStream(); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file.getPath()+fileName+endWith)); byte[] bs = new byte[2048*2048]; while((is.read(bs))!=-1){ bos.write(bs); } bos.flush(); if(is != null) is.close(); if(bos != null) bos.close(); } }

&n