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);
        }
        //获取所有的
  • 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(); } }
  • 小生初来乍到 有什么写的不好的地方 请大佬们多多指教 感谢感谢!

    你可能感兴趣的:(java)