我想从网页上下载一些图片,为此我编写了一个爬虫程序。我为这个页面测试了几个爬虫,但没有一个能像我想的那样工作。
在第一步中,我收集了770+相机型号的链接(parent_url
),然后我正在考虑收集每个链接的图像(child_urls
)。但是,该页面的组织方式是child_urls
返回与parent_url
相同的html。
下面是我收集相机链接的代码:
public List<String> html_compiler(String url, String exp, String atr){
List<String> outs = new ArrayList<String>();
try {
Document doc = Jsoup.connect(url).get();
Elements links = doc.select(exp);
for (Element link : links) {
outs.add(link.attr(atr));
System.out.println("nlink : " + link.attr(atr));
}
} catch (IOException | SelectorParseException e) {
e.printStackTrace();
}
return outs;
}
在这段代码中,我收集了链接
String expCam = "tr[class='gallery cameras'] > td[class='title'] > a[href]";
String url = "https://www.dpreview.com/sample-galleries?category=cameras";
String atr = "href";
List<String> cams = html_compiler(url, exp, atr); // This gives me the links of individual cameras
String exp2 = "some expression";
html_compiler(cams.get(0), exp2, "src"); // --> this should give me image links of the first
//camera but webpage returns same html as above
我该如何解决这个问题?我很想听听其他根据相机型号分类图像的页面。(Flickr除外)
编辑:在java中,下面两个链接给出了相同的html。
https://www.dpreview.com/sample-galleries?category=cameras https://www.dpreview.com/sample-galleries/2653563139/nikon-d1-review-samples-one要了解如何获得图像链接,了解页面在浏览器中的加载方式非常重要。如果单击画廊链接,将触发一个javascript事件处理程序。然后,创建的图像查看器从数据服务器加载图像。图像链接是通过javascript请求的,因此通过解析html是不可见的。图像链接的请求URL是https://www.dpreview.com/sample-galleries/data/get-gallery
,以获得在图库中的图像,您必须添加图库id。画廊id由画廊链接的href
属性提供。链接看起来像https://www.dpreview.com/sample-galleries/2653563139/nikon-d1-review-samples-one
。在本例中,2653563139
是画廊id。获取上面给出的链接,并将带有?galleryId=2653563139
的画廊id添加到URL的末尾,以获得包含创建画廊所需的所有数据的json对象。在images
数组中查找url
字段来获取图像。
总结:
从href
属性获得的链接:https://www.dpreview.com/sample-galleries/2653563139/nikon-d1-review-samples-one
图库id: 2653563139
请求url: https://www.dpreview.com/sample-galleries/data/get-gallery
需要的json对象:https://www.dpreview.com/sample-galleries/data/get-gallery?galleryId=2653563139
你在json对象中寻找的url: "url":"https://3.img-dpreview.com/files/p/TS1800x1200~sample_galleries/2653563139/7864344228.jpg"
最后你的图片链接:https://3.img-dpreview.com/files/p/TS1800x1200~sample_galleries/2653563139/7864344228.jpg