java手机壁纸_用java爬取手机壁纸

傷城~ 2023-09-26 14:29 74阅读 0赞

JFrame包,循环爬取图片然后下载图片

  1. public class DownWallpaper extends JFrame implements ActionListener{
  2. private JButton down = null;
  3. public DownWallpaper(){
  4. down = new JButton("下载手机壁纸");
  5. down.setFont(new Font("微软雅黑",Font.ITALIC,20));
  6. down.addActionListener(this);
  7. this.setResizable(false);
  8. this.add(down);
  9. this.setTitle("高清壁纸下载");
  10. this.setSize(250, 150);
  11. this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  12. this.setLocationRelativeTo(null);
  13. this.setVisible(true);
  14. }
  15. @Override
  16. public void actionPerformed(ActionEvent e) {
  17. if (e.getSource()==down) {
  18. try {
  19. JOptionPane.showMessageDialog(this, "正在下载请勿关闭主窗体!");
  20. JOptionPane.showMessageDialog(this, "详细信息请查看:https://sj.enterdesk.com/");
  21. JOptionPane.showMessageDialog(this, "下载完成后请到:d:/img下查看");
  22. load("https://sj.enterdesk.com/");
  23. } catch (Exception e1) {
  24. e1.printStackTrace();
  25. }
  26. }
  27. }
  28. public static void main(String[] args) {
  29. new DownWallpaper();
  30. }
  31. /**
  32. * 加载链接
  33. * @param urls
  34. * @throws Exception
  35. */
  36. public static void load(String urls) throws Exception{
  37. Connection connect = Jsoup.connect(urls);
  38. Document document = connect.get();
  39. Elements links = document.getElementsByTag("img");
  40. //循环爬取图片
  41. for(Element link : links){
  42. String url = link.attr("src");//下载的url
  43. String endWith = url.substring(url.lastIndexOf("."));//文件后缀名
  44. String fileName = link.absUrl("alt").substring(link.absUrl("alt").lastIndexOf("/"));//文件名
  45. download(url,endWith,fileName);
  46. }
  47. //获取所有的<li>
  48. Elements select = document.select("a");
  49. Elements addClass = select.addClass("next_p");
  50. for (Element element : addClass) {
  51. if (element.text().equals("下一页")) {
  52. //获取超链接
  53. String attr = element.attr("href");
  54. //递归循环下载
  55. load(attr);
  56. }else{
  57. continue;
  58. }
  59. }
  60. }
  61. /**
  62. * 下载图片
  63. * @param url
  64. */
  65. public static void download(String url,String endWith,String fileName) throws Exception{
  66. File file = new File("d:/img/");
  67. if (!file.exists()){
  68. file.mkdir();
  69. }else{
  70. file.delete();
  71. file.mkdir();
  72. }
  73. URL url2 = new URL(url);
  74. InputStream is = url2.openConnection().getInputStream();
  75. BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file.getPath()+fileName+endWith));
  76. byte[] bs = new byte[2048*2048];
  77. while((is.read(bs))!=-1){
  78. bos.write(bs);
  79. }
  80. bos.flush();
  81. if(is != null) is.close();
  82. if(bos != null) bos.close();
  83. }
  84. }

注意目录

注意地址

注意导入java包,用java爬取手机壁纸完成。

发表评论

表情:
评论列表 (有 0 条评论,74人围观)

还没有评论,来说两句吧...

相关阅读