image.png

    1. import org.jsoup.Jsoup;
    2. import org.jsoup.nodes.Document;
    3. import org.jsoup.nodes.Element;
    4. import org.jsoup.select.Elements;
    5. import java.io.*;
    6. import java.net.MalformedURLException;
    7. import java.net.URL;
    8. import java.nio.charset.Charset;
    9. import java.util.concurrent.ExecutorService;
    10. import java.util.concurrent.Executors;
    11. public class url {
    12. public static void main(String[] args) throws IOException {
    13. //存放 url地址
    14. String url = "https://car.autohome.com.cn/pic/series/102.html#pvareaid=3454438";
    15. URL u = new URL(url);
    16. InputStream inputStream = u.openStream();
    17. //一行一行读
    18. BufferedReader bf = new BufferedReader(new InputStreamReader(inputStream,"GBK"));
    19. //查看电脑 默认编码
    20. System.out.println(Charset.defaultCharset());
    21. String line;
    22. StringBuilder sb = new StringBuilder();
    23. while ((line=bf.readLine())!=null){
    24. sb.append(line);
    25. }
    26. //用Jsoup解析html文件
    27. Document parse = Jsoup.parse(sb.toString());
    28. //得到所有的 img 元素集合
    29. Elements img = parse.select("img");
    30. ExecutorService es = Executors.newFixedThreadPool(20);
    31. System.out.println(img.size());
    32. for (int i = 0; i <img.size() ; i++) {
    33. Element element = img.get(i);
    34. String path = element.attr("src");
    35. System.out.println(path);
    36. //调用下载 方法
    37. es.submit(new Runnable() {
    38. @Override
    39. public void run() {
    40. try {
    41. downloda(path);
    42. } catch (IOException e) {
    43. e.printStackTrace();
    44. }
    45. }
    46. });
    47. }
    48. }
    49. public static void downloda(String url) throws IOException {
    50. if (url.indexOf("/")==0){
    51. url="https:"+url;
    52. }
    53. URL u = new URL(url);
    54. InputStream inputStream = u.openStream();
    55. int begin = url.lastIndexOf("/");
    56. //car2.autoimg.cn/cardfs/product/g20/M12/7D/FF/480x360_0_q95_c42_autohomecar__ChsElWDoSlWAESRaACQdsSr_S1I935.jpg
    57. String filename = url.substring(begin + 1);
    58. FileOutputStream fos = new FileOutputStream("D:/pic/"+filename);
    59. byte[] bytes = new byte[1024];
    60. int len ;
    61. while ((len=inputStream.read(bytes))>0){
    62. fos.write(bytes,0,len);
    63. }
    64. System.out.println("over");
    65. }
    66. }