Url没有在网页中返回正确的html(对于我的Java爬虫)
我想从网页上下载一些图像,为此我正在编写爬网程序。我测试了这个页面的几个抓取工具,但没有工作,因为我想。Url没有在网页中返回正确的html(对于我的Java爬虫)
第一步,我收集了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
要了解如何获取图像的链接,知道很重要的是如何加载页面在浏览器中。如果你点击gallerie链接,一个JavaScript事件处理程序将被触发。创建的图像查看器然后从数据服务器加载图像。图像链接是通过javascript请求的,因此仅通过解析html就不可见。图像链接的请求URL为https://www.dpreview.com/sample-galleries/data/get-gallery
,以获取gallerie中的图像,您必须添加gallerie id。画廊编号由画廊链接的href
属性提供。链接看起来像https://www.dpreview.com/sample-galleries/2653563139/nikon-d1-review-samples-one
。在这种情况下,2653563139
是画廊编号。取上面给出的链接,并将URL编号?galleryId=2653563139
添加到URL的末尾以获取包含创建画廊所需的所有数据的json对象。查找images
阵列中的url
字段以获取图像。
总结:
您从href
属性获取链接:https://www.dpreview.com/sample-galleries/2653563139/nikon-d1-review-samples-one
的gallerie 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":"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
评论。
这是非常好的解释。链接中的图像数量与图库链接中给出的数量相匹配,所以它看起来非常稳固。谢谢 – smttsp
你可以尝试使用'abs:href' attr? [看看这里的例子](http://stackoverflow.com/a/14205979/1992780)。 –
@DavidePastore都返回相同的结果,我不认为它是关于绝对链接。 – smttsp
第二个链接似乎在加载图片的浏览器中触发了一些javascript。尝试使用浏览器中的调试工具打开这两个链接。 (Ctrl + Shift + Q在Firefox中)你必须找出图片链接是如何在页面源的某个地方创建的。 – kaetzacoatl