Jsoup图像标记提取

Raj*_*esh 2 java jsoup

我需要使用此html中的jsoup提取图像标记

<div class="picture"> 
    <img src="http://asdasd/aacb.jpgs" title="picture" alt="picture" />
</div>
Run Code Online (Sandbox Code Playgroud)

我需要提取这个img标签的src ...我正在使用这个代码我得到空值

Element masthead2 = doc.select("div.picture").first();
String linkText = masthead2.outerHtml();
Document doc1 = Jsoup.parse(linkText);
Element masthead3 = doc1.select("img[src]").first();
String linkText1 = masthead3.html();
Run Code Online (Sandbox Code Playgroud)

Jon*_*ley 6

这是获取图像源属性的示例:

public static void main(String... args) {
    Document doc = Jsoup.parse("<div class=\"picture\"><img src=\"http://asdasd/aacb.jpgs\" title=\"picture\" alt=\"picture\" /></div>");
    Element img = doc.select("div.picture img").first();
    String imgSrc = img.attr("src");
    System.out.println("Img source: " + imgSrc);
}
Run Code Online (Sandbox Code Playgroud)

div.picture img选择器认定在div下的图像元素.

元素的主要提取方法是:

  • attr(name),它获取元素属性的值,
  • text(),获取元素的文本内容(例如,在<p>Hello</p>text()中是"Hello"),
  • html(),它获取元素的内部HTML(<div><img></div>html()= <img>),和
  • outerHtml(),获取元素完整的HTML(<div><img></div>html()= <div><img></div>)

您不需要像在当前示例中那样重新分析HTML,要么使用更具体的选择器在第一个位置选择正确的元素,要么按下element.select(string)方法以关闭winnow.