[英][JAVA]Get html link from webpage
我想使用java獲取這張圖片中的鏈接,圖片如下。 該網頁中還有幾個鏈接。 我在stackoverflow上找到了這段代碼,但我不明白如何使用它。
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class weber{
public static void main(String[] args)throws Exception{
String url = "http://www.skyovnis.com/category/ufology/";
Document doc = Jsoup.connect(url).get();
/*String question = doc.select("#site-inner").text();
System.out.println("Question: " + question);*/
Elements anser = doc.select("#container .entry-title a");
for (Element anse : anser){
System.out.println("Answer: " + anse.text());
}
}
}
代碼是從我發現的原始代碼中編輯的。 請幫忙。
對於您的網址,以下代碼工作正常。
public static void main(String[] args) {
Document doc;
try {
// need http protocol
doc = Jsoup.connect("http://www.skyovnis.com/category/ufology/").userAgent("Mozilla").get();
// get page title
String title = doc.title();
System.out.println("title : " + title);
// get all links (this is what you want)
Elements links = doc.select("a[href]");
for (Element link : links) {
// get the value from href attribute
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text());
}
} catch (IOException e) {
e.printStackTrace();
}
}
輸出是
title : Ufology
link : http://www.shop.skyovnis.com/
text : Shop
link : http://www.shop.skyovnis.com/product-category/books/
text : Books
以下代碼按文本過濾鏈接。
for (Element link : links) {
if(link.text().contains("Arecibo Message"))//find the link with some texts
{
System.out.println("here is the element you need");
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text());
}
}
建議在 Jsoup 中指定“userAgent”,以避免 HTTP 403 錯誤消息。
文檔 doc = Jsoup.connect(" http://anyurl.com ").userAgent("Mozilla").get();
“Onna malli 法師 yuthukama kala。”
參考:
https://www.mkyong.com/java/jsoup-html-parser-hello-world-examples/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.