[英]Regex to parse html source in JSoup
我正在嘗試從網頁源文件中獲取值,這是我擁有的html規則
e=d.select("li[id=result_48]");
e=d.select("div[id=result_48]");
這是html標記
<li id="result_48" data-asin="0781774047" class="s-result-item">
<div id="result_48" data-asin="0781774047" class="s-result-item">
我想做的是代替“ li”或“ div”的任何內容,我想獲取id內的值..因此我想使用RegX代替“ li”或“ div”
因此,Jsoup元素應檢查id = result_48,如果出現類似的情況,我需要數據。 我怎樣才能做到這一點。
提前致謝
測試了不同順序的屬性。 可能會遺漏某些情況,因此請使用您的實際數據進行測試。 假設id屬性中沒有空格和引號。
public static void main(String[] args) throws Exception {
String[] lines = {
"<li id=\"result_48\" data-asin=\"0781774047\" class=\"s-result-item\">",
"<div id=\"result_48\" data-asin=\"0781774047\" class=\"s-result-item\">",
"<div data-asin=\"0781774047\" id=\"result_48\" class=\"s-result-item\">",
"<div data-asin=\"0781774047\" class=\"s-result-item\" id=\"result_48\">" };
for (String str : lines) {
System.out.println(extractId(str));
}
}
private static String extractId(String line) {
String regex = "";
regex = regex + "(?:[<](?:li|div)).*id=\""; // match start until id="
regex = regex + "([^\\s^\"]+)"; // capture the id inside quotes (exclude
// spaces and quote)
regex = regex + "(?:.*\">)"; // match any characters until the end ">
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(line);
if (matcher.matches()) {
return matcher.group(1);
}
return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.