从嵌套 div 和 JSOUP 中的标签中提取图像源
Extract Image source from nested div and a tag in JSOUP
<div class='ym-gbox adds-header'>
<a href='javascript:(void);' >
<a href="http://epaper.thedailystar.net/" target="_blank">
<img src="http://epaper.thedailystar.net/images/edailystar.png" alt="edailystar" style="float: left; width: 100px; margin-top: 15px;">
</a>
<a href="http://www.banglalink.com.bd/celebrating10years" target="_blank" style="display:block;float: right;">
<img width="490" height="60" src="http://bd.thedailystar.net/upload/ads/2015/02/12/BD-News_490x60.gif" alt="banglalink" >
</a>
</a>
</div>
这是 html 部分。从这里我想使用 android 中的 jsoup 提取源地址为 src="http://epaper.thedailystar.net/images/edailystar.png" 的图像标签的图像源。但是我失败了。如果有人给出答案,我会感谢他。
这是我的代码
Document document = Jsoup.connect(url).get();
Elements img = document.select("div[class=ym-gbox adds-header]").first().select("a[href=http://epaper.thedailystar.net/] > img[src]");
String imgSrc = img.attr("src");
既然你没有提到url
,我假设url
是http://epaper.thedailystar.net/index.php
Document doc = Jsoup.connect("http://epaper.thedailystar.net/index.php").timeout(10*1000).get();
Elements div = doc.select("div.logo");
Elements get = div.select("img");
System.out.println(get.attr("abs:src"));
输出:
http://epaper.thedailystar.net/images/edailystar.png
您必须遍历元素以选择适合您需要的元素。像这样:
Elements elements = document.getElementsByTag("img");
for (Element element : elements) {
if (element.attr("src").endsWith("png")) {
System.out.println(element.attr("src"));
}
}
<div class='ym-gbox adds-header'>
<a href='javascript:(void);' >
<a href="http://epaper.thedailystar.net/" target="_blank">
<img src="http://epaper.thedailystar.net/images/edailystar.png" alt="edailystar" style="float: left; width: 100px; margin-top: 15px;">
</a>
<a href="http://www.banglalink.com.bd/celebrating10years" target="_blank" style="display:block;float: right;">
<img width="490" height="60" src="http://bd.thedailystar.net/upload/ads/2015/02/12/BD-News_490x60.gif" alt="banglalink" >
</a>
</a>
</div>
这是 html 部分。从这里我想使用 android 中的 jsoup 提取源地址为 src="http://epaper.thedailystar.net/images/edailystar.png" 的图像标签的图像源。但是我失败了。如果有人给出答案,我会感谢他。
这是我的代码
Document document = Jsoup.connect(url).get();
Elements img = document.select("div[class=ym-gbox adds-header]").first().select("a[href=http://epaper.thedailystar.net/] > img[src]");
String imgSrc = img.attr("src");
既然你没有提到url
,我假设url
是http://epaper.thedailystar.net/index.php
Document doc = Jsoup.connect("http://epaper.thedailystar.net/index.php").timeout(10*1000).get();
Elements div = doc.select("div.logo");
Elements get = div.select("img");
System.out.println(get.attr("abs:src"));
输出:
http://epaper.thedailystar.net/images/edailystar.png
您必须遍历元素以选择适合您需要的元素。像这样:
Elements elements = document.getElementsByTag("img");
for (Element element : elements) {
if (element.attr("src").endsWith("png")) {
System.out.println(element.attr("src"));
}
}