Jsoup выбирает данные таблицы

На всю жизнь я не могу понять, как выбрать img src, используя jsoup ссылку, заканчивающуюся на «51u1FaI-FHL._SL500_AA300_.jpg».

Я пробовал несколько вещей, но ни одна из них не сработала. Любая помощь?

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> 

person user793728    schedule 11.06.2011    source источник


Ответы (2)


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

    }
person ag112    schedule 11.06.2011

Проблема здесь, похоже, в том, что Amazon возвращает в jsoup другой HTML, чем в ваш браузер, на основе запроса UserAgent.

Я установил UserAgent на известный браузер и выбрал элемент, используя идентификатор #prodImage, и получил результат OK.

E.g.

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-кода вашего браузера (поскольку серверы могут возвращать другой HTML, а исходный код показывает до того, как HTML был приведен в порядок и встроен в DOM).

Надеюсь это поможет!

person Jonathan Hedley    schedule 13.06.2011