我想从网页下载一些图像,为此我正在编写一个爬虫。我为此页面测试了几个爬虫,但没有一个按我想要的方式工作。
第一步,我收集了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-gallery/data/get-gallery
要获取画廊中的图像,您必须添加画廊 ID。图库 ID 由图库链接的 href
属性提供。这些链接类似于 https://www.dpreview.com/sample-galleries/2653563139/nikon-d1-review-samples-one
。在本例中,2653563139
是画廊 ID。获取上面给出的链接,并将画廊 ID 与 ?galleryId=2653563139
添加到 URL 末尾,以获取包含创建画廊所需的所有数据的 json 对象。查找 images
数组中的 url
字段以获取图像。
总结一下:
从href
属性获得的链接:https://www.dpreview.com/sample-galleries/2653563139/nikon-d1-review-samples-one
画廊ID:2653563139
请求网址:https://www.dpreview.com/sample-galleries/data/get-gallery
您需要的json对象:https://www.dpreview.com/sample-galleries/data/get-gallery?galleryId=2653563139
您在 json 对象中查找的网址:"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
如果您需要进一步解释,请发表评论。
关于java - Url 未在网页中返回正确的 html(对于我的 Java 爬虫),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38974863/