【问题标题】:parsing an image url from an html file从 html 文件中解析图像 url
【发布时间】:2012-06-16 03:11:20
【问题描述】:
我想搜索一个 html 文件,然后获取该页面上图像的 url。然后应将此 url 保存为字符串 - 仅此而已。问题是我真的不知道如何开始。
我的应用当然知道图片所在页面的 url。
以这个网址为例:
在这个页面上,我需要大图像的 url 作为字符串。当我查看源代码时,我可以找到该 url,但我不知道如何编码 - 这是我需要的 url:
(仅限引号内的文字)。
【问题讨论】:
标签:
java
android
html
image
parsing
【解决方案1】:
使用JSoup。它是一个 HTML 解析器,允许您使用 css 选择器(如 jQuery)访问 DOM 元素。
// Parse your HTML:
// 1. From string:
Document doc = JSoup.parse(htmlAsString);
// 2. Or from an URL:
Document doc = JSoup.connect("http://my.awesome.site.com/").get();
// Then select images inside it:
Elements images = doc.select("img");
// Then iterate
for (Element el : images) {
String imageUrl = el.attr("src");
// TODO: Do something with the URL
}
【解决方案2】:
好的,这完成了 :) 我现在正在获取图片网址:
public class jSoupEx {
private static final String elements = null;
public static void main(String args[]){
try {
Document doc = Jsoup.connect("http://***/index.php/Datei:***.jpg").get();
Element image = doc.select("img").first();
String url = image.absUrl("src");
System.out.println(url);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}