[英]How to get the attribute “href” from an “a” tag in Jsoup?
我正在做一個網絡抓取項目,基本上是從Google圖片中獲取圖片。 為了獲得圖像src,我使用
Element.attr("href")
但是,它返回
#
我的密碼
Document shivWall = Jsoup.connect(searchURL).get();
Elements smallImgElements = shivWall.getElementsByClass("rg_bx rg_di rg_el ivg-i");
smallImgElements.get(0).select("a.rg_l").get(0).attr("href");
我嘗試了許多方法,但沒有一個起作用。 我什至通過將attr參數更改為某個隨機值來再次檢查,它按預期返回null。 但是,對於“ href”,它僅返回“#”。 請幫忙。
為了從網站獲取標簽的src屬性,您可以嘗試使用以下代碼段
public class DownloadImages {
//The url of the website. This is just an example
private static final String webSiteURL = "http://www.supercars.net/gallery/119513/2841/5.html";
//The path of the folder that you want to save the images to
private static final String folderPath = "<FOLDER PATH>";
public static void main(String[] args) {
try {
//Connect to the website and get the html32
Document doc = Jsoup.connect(webSiteURL).get();
//Get all elements with img tag ,
Elements img = doc.getElementsByTag("img");
for (Element el : img) {
//for each element get the srs url
String src = el.absUrl("src");
System.out.println("Image Found!");
System.out.println("src attribute is : "+src);
getImages(src);
}
} catch (IOException ex) {
System.err.println("There was an error");
Logger.getLogger(DownloadImages.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static void getImages(String src) throws IOException {
String folder = null;
//Exctract the name of the image from the src attribute
int indexname = src.lastIndexOf("/");
if (indexname == src.length()) {
src = src.substring(1, indexname);
}
indexname = src.lastIndexOf("/");
String name = src.substring(indexname, src.length());
System.out.println(name);
//Open a URL Stream
URL url = new URL(src);
InputStream in = url.openStream();
OutputStream out = new BufferedOutputStream(new FileOutputStream( folderPath+ name));
for (int b; (b = in.read()) != -1;) {
out.write(b);
}
out.close();
in.close();
}
}
這是您可以使用Jsoup從網站下載圖像的方法。
希望這可以幫助。
如果您將檢查通過Document shivWall = Jsoup.connect(searchURL).get();
獲得的html結構Document shivWall = Jsoup.connect(searchURL).get();
您會發現, #
是href
參數的初始值。 加載頁面后,將使用javascript動態添加網址。 Jsoup無法處理此問題。
要獲取網址,您可以使用以下代碼:
for(Element e : shivWall.select(".rg_meta.notranslate")) {
Gson gson = new Gson();
Map imageData = gson.fromJson(e.text(), Map.class);
System.out.println(imageData.get("ou"));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.