從html源碼中獲取圖片鏈接地址和視頻鏈接地址

從HTML源碼獲取資源地址

1、img標籤截取正則表達式


String PICTURE_REGEX = "<img\\b[^<>]*?\\bsrc[\\s\\t\\r\\n]*=[\\s\\t\\r\\n]*[\"\"']?[\\s\\t\\r\\n]*(?<imgUrl>[^\\s\\t\\r\\n\"\"'<>]*)[^<>]*?/?[\\s\\t\\r\\n]*>";

2、video標籤截取正則表達式


String VIDEO_REGEX = "<video\\b[^<>]*?\\bsrc[\\s\\t\\r\\n]*=[\\s\\t\\r\\n]*[\"\"']?[\\s\\t\\r\\n]*(?<videoUrl>[^\\s\\t\\r\\n\"\"'<>]*)[^<>]*?/?[\\s\\t\\r\\n]*>";

3、資源地址截取正則表達式


String SRC_REGEX = "src\\s*=\\s*\"?'?(.*?)(\"|'|>|\\s+)";

4、截取代碼


public static final String PICTURE_REGEX = "<img\\b[^<>]*?\\bsrc[\\s\\t\\r\\n]*=[\\s\\t\\r\\n]*[\"\"']?[\\s\\t\\r\\n]*(?<imgUrl>[^\\s\\t\\r\\n\"\"'<>]*)[^<>]*?/?[\\s\\t\\r\\n]*>";

public static final String VIDEO_REGEX = "<video\\b[^<>]*?\\bsrc[\\s\\t\\r\\n]*=[\\s\\t\\r\\n]*[\"\"']?[\\s\\t\\r\\n]*(?<videoUrl>[^\\s\\t\\r\\n\"\"'<>]*)[^<>]*?/?[\\s\\t\\r\\n]*>";

public static final String SRC_REGEX = "src\\s*=\\s*\"?'?(.*?)(\"|'|>|\\s+)";
/**
  * 從html源碼中獲取圖片或視頻鏈接地址
  * @param htmlStr 目標html字符串
  * @return
  */
public static Set<String> getImgOrVideoSrc(String htmlStr) {
        Set<String> pics = new HashSet<>(); //用set接收可以有效去重
        String img = "";
        Pattern p_image = p_image = Pattern.compile(PICTURE_REGEX, Pattern.CASE_INSENSITIVE);
        // 圖片鏈接地址
        Matcher m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            // 得到<img />數據
            img = m_image.group();
            // 匹配<img>中的src數據
            Matcher m = Pattern.compile(SRC_REGEX).matcher(img);
            while (m.find()) {
                pics.add(m.group(1));
            }
        }
        return pics;
    }

獲取到資源url想下載,可以參考一下博客
HttpClient 通過資源URL下載資源.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章