簡體   English   中英

Jsoup圖像標記提取

[英]Jsoup image tag extraction

我需要使用此html中的jsoup提取圖像標記

<div class="picture"> 
    <img src="http://asdasd/aacb.jpgs" title="picture" alt="picture" />
</div>

我需要提取這個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();

這是獲取圖像源屬性的示例:

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);
}

div.picture img選擇器在div下找到image元素。

元素的主要提取方法是:

  • 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 down。

使用以下代碼,我可以正確提取圖像:

    Document doc = Jsoup.parse("<div class=\"picture\"> <img src=\"http://asdasd/aacb.jpgs\" title=\"picture\" alt=\"picture\" /> </div>");

    Element elem = doc.select("div.picture img").first();

    System.out.println("elem: " + elem.attr("src"));

我正在使用最新的jsoup版本1.2.2

也許你正在嘗試打印像img這樣的空標簽的內部html。

從文檔:“html() - 檢索元素的內部HTML”。

對於html的第二部分,您可以使用:

    Document doc2 = Jsoup.parse("<tr>  <td class=\"blackNoLine\" nowrap=\"nowrap\" valign=\"top\" width=\"25\" align=\"left\"><b>CAST: </b></td>  <td class=\"blackNoLine\" valign=\"top\" width=\"416\">Jay, Shazahn Padamsee&nbsp;</td>  </tr>");
    Elements trElems = doc2.select("tr");
    if (trElems != null) {
        for (Element element : trElems) {
            Element secondTd = element.select("td").get(1);

            System.out.println("name: " + secondTd.text());
        }
    }

其中印有“Jay,Shazahn Padamsee”字樣。

<tr>  <td class="blackNoLine" nowrap="nowrap" valign="top" width="25" align="left"><b>CAST: </b></td>  <td class="blackNoLine" valign="top" width="416">Jay, Shazahn Padamsee&nbsp;</td>  </tr>

您可以使用:

Document doc = Jsoup.parse(...);
Elements els = doc.select("td[class=blackNoLine]");
Element el= els.get(1);
String castName = el.text();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM