[英]How to get all the links inside a specific div from a webpage using Jsoup?
[英]get all links from a div with JSoup
基本上,我是使用 Jsoup 來解析一個站點,我想從以下 html 中獲取所有鏈接:
<ul class="detail-main-list"> <li> <a href="/manga/toki_wa/v01/c001/1.html" title="Toki wa... Vol.01 Ch.001 -Toki wa... target="_blank"> Dis Be the link</a> </li> </ul>
知道怎么做嗎?
直接來自 jsoup.org,就在那里,您首先看到的是:
Document doc = Jsoup.connect("https://en.wikipedia.org/").get();
log(doc.title());
Elements newsHeadlines = doc.select("#mp-itn b a");
for (Element headline : newsHeadlines) {
log("%s\n\t%s",
headline.attr("title"), headline.absUrl("href"));
}
將其修改為您需要的內容似乎微不足道:
Document doc = Jsoup.connect("https://en.wikipedia.org/").get();
Elements anchorTags = doc.select("ul.detail-main-list a");
for (Element anchorTag : anchorTags) {
System.out.println("Links to: " + anchorTag.attr("href"));
System.out.println("In absolute form: " + anchorTag.absUrl("href"));
System.out.println("Text content: " + anchorTag.text());
}
ul.detail-main-list a
一部分就是所謂的選擇器字符串。 關於這些的真正簡短教程:
foo
表示:任何具有該標簽名稱的 HTML 元素,即<foo></foo>
。.bar
表示:任何帶有 class bar
的 HTML 元素,即<foo class="bar baz"></foo>
#bar
表示:任何具有 id bar
的 HTML 元素,即<foo id="bar">
ul.detail-main-list
匹配任何在其類列表中具有字符串detail-main-list
的<ul>
標記。ab
表示:所有匹配 'b' 選擇且具有匹配 'a' 作為父級的東西。 所以ul a
匹配所有在它們周圍有一個<ul>
標簽的<a>
標簽。JSoup 文檔非常好。
您可以從任何網站以這種方式創建特定的 a href 鏈接。
public static void main(String[] args) {
String htmlString = "<html>\n" +
" <head></head>\n" +
" <body>\n" +
"<ul class=\"detail-main-list\">\n" +
" <li> \n" +
" <a href=\"/manga/toki_wa/v01/c001/1.html\" title=\"Toki wa... Vol.01 Ch.001 -Toki wa... target=\"_blank\"> Dis Be the link</a>\n" +
" </li> \n" +
"</ul>" +
" </body>\n" +
"</html>"
+ "<head></head>";
Document html = Jsoup.parse(htmlString);
Elements elements = html.select("a");
for(Element element: elements){
System.out.println(element.attr("href"));
}
}
Output:
/manga/toki_wa/v01/c001/1.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.