簡體   English   中英

Jsoup 選擇表數據

[英]Jsoup selecting table data

對於我的一生,我無法弄清楚如何使用 jsoup 以“51u1FaI-FHL._SL500_AA300_.jpg”結尾的鏈接來 select img src。

我嘗試了多種方法,但都沒有奏效。 有什么幫助嗎?

doc1 = Jsoup.connect("http://www.amazon.com/gp/product/B0051HDDO2?ie=UTF8&ref=mas_faad").timeout(20000).get();
Element table = doc1.select("table[class=productImageGrid]").first()
Iterator<Element> ite = table.select("td[height=300]").iterator();

謝謝, 科迪

<table style="text-align: center;" border="0" cellpadding="0" cellspacing="0" width="300"> 
  <tr> 
    <td id="prodImageCell" height="300" width="300" style="padding-bottom: 10px;"><img onclick="if(0 ){ async_openImmersiveView(event);} else {openImmersiveView(event);}" class="prod_image_selector" style="cursor:pointer;" onload="if (typeof uet == 'function') { uet('af'); }" **src="http://ecx.images-amazon.com/images/I/51u1FaI-FHL._SL500_AA300_.jpg"** id="prodImage"/><div id="prodImageCellInner" style="position: relative; height:0px; "><!--Comment for IE as it is empty div--></div></td> 
    <td id="prodVideoClick" style="display:none"></td> 
    <img id="loadingImage" src=http://g-ecx.images-amazon.com/images/G/01/ui/loadIndicators/loading-large_boxed._V192195297_.gif style="position: absolute;  z-index: 200; display:none"> 
 </tr> 
  <tr> 
    <td class="tiny" style="padding-bottom: 5px;">&nbsp;<span id="prodImageCaption" style="color: #666666; font-size: 10px;">Click for larger image and other views</span>&nbsp;</td> 
  </tr> 
 </table> 

@user793728:試試這個:-

document = Jsoup.connect("http://www.amazon.com/gp/product/B0051HDDO2?ie=UTF8&ref=mas_faad").timeout(20000).get();

Elements elements =document.select(".prod_image_selector");
    for (Element element : elements){
        Attributes imageAttributes=element.attributes();
        for (Attribute attribute: imageAttributes){
            if(attribute.getKey().equals("src")){
            String imageURL=attribute.getValue();
            }
        }

    }

這里的問題似乎是亞馬遜根據請求 UserAgent 將不同的 HTML 返回到 jsoup,而不是返回到您的瀏覽器。

我將 UserAgent 設置為已知瀏覽器,並使用#prodImage ID 選擇元素,結果正常。

例如

Document doc = Jsoup.connect("http://www.amazon.com/gp/product/B0051HDDO2?ie=UTF8&ref=mas_faad")
        .timeout(20000)
        .userAgent("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7) AppleWebKit/534.30 (KHTML, like Gecko) Chrome/12.0.742.91 Safari/534.30")
        .get();
Element img = doc.select("#prodImage").first();
System.out.println(img.attr("src"));

返回http://ecx.images-amazon.com/images/I/51u1FaI-FHL._SL500_AA300_.jpg

為了解決此類問題,我建議輸出doc.html()並查看檢索到的、已解析的 HTML,因為它可能與瀏覽器的視圖源 HTML 不同(因為服務器可以返回不同的 Z4C4AD5FCA2E7A3FAA44DBB 和視圖源在 HTML 被整理並內置到 DOM 之前)。

希望這可以幫助!

暫無
暫無

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

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