[英]Downloading a file with HtmlUnit. Download button has no (seemingly) accessible link
我是編程新手,找不到適合我問題的答案,並且不確定該向何處轉向。 如標題中所述,我希望使用Java中的HtmlUnit下載文件,但是頁面上的下載按鈕沒有可訪問的href或onclick。 按鈕如下:
<button class="btn btn-download btn-primary pull-right" id="eta_download" style="display: block;"> <span class="glyphicon glyphicon-download-alt"></span> </button>
單擊此按鈕會使普通瀏覽器在短時間內進行一些處理和加載,然后打開一個選項卡,該選項卡觸發下載包含tiff衛星圖像的gzip文件。 我正在Swing應用程序中執行此操作。
誰能幫我讓這個工作?
我的代碼如下:
// Call from whithin new Thread. Get the download
private void getDownload(String latitude, String longitude, String start, String end) throws Exception
{
// Create the browser
final WebClient webClient = new WebClient(BrowserVersion.CHROME);
// Report to user. Loading page...
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
reportLabel.setText("Loading EEFLUX...");
}
});
// Load page
HtmlPage page = webClient.getPage("https://eeflux-level1.appspot.com/");
// Report to user change in state
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
reportLabel.setText("Filling in values");
}
});
// Get Latitude, Lomgitude and Date Fields
HtmlInput latitudeField = (HtmlInput) page.getElementById("latitude");
HtmlInput longitudeField = (HtmlInput) page.getElementById("longitude");
HtmlInput date_start_Field = (HtmlInput) page.getElementById("date_start");
HtmlInput date_end_Field = (HtmlInput) page.getElementById("date_end");
// Set the values of fields to that passed into method
latitudeField.setAttribute("value", latitude);
longitudeField.setAttribute("value", longitude);
date_start_Field.setAttribute("value", start);
date_end_Field.setAttribute("value", end);
// Get the Search "Button" then click
HtmlAnchor search = (HtmlAnchor) page.getHtmlElementById("searchForImages");
page = search.click();
// wait for Javascripts jobs to finish
JavaScriptJobManager manager = page.getEnclosingWindow().getJobManager();
for (int i = 0; manager.getJobCount() > 7; i++)
{
final int j = i;
// Report to user change in state
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
reportLabel.setText("Loading after Search: " + j);
}
});
Thread.sleep(1000);
}
// Get the list of regions Satellites captured and click to open dropdown
HtmlDivision image_dropdown = (HtmlDivision) page.getElementById("image_dropdown");
image_dropdown.click();
// Get the list of regions
HtmlUnorderedList region_list = (HtmlUnorderedList) image_dropdown.getLastElementChild();
// get iterator for list
Iterator<DomElement> web_list = region_list.getChildElements().iterator();
// Report to user change in state
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
reportLabel.setText("Accessing region list");
}
});
// for each Element, download Actual ET image (and later Grass Reference)
while(web_list.hasNext())
{
DomElement region = web_list.next();
System.out.println(region.getTextContent());
HtmlPage page2 = region.click();
// wait for Javascripts jobs to finish
manager = page2.getEnclosingWindow().getJobManager();
for (int i = 0; manager.getJobCount() > 2; i++)
{
final int j = i;
// Report to user
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
reportLabel.setText("Loading Image Type page: " + j);
}
});
System.out.println(manager.getJobCount());
Thread.sleep(1000);
}
// Get the Actual ET download Button
HtmlButton ETButton = page2.getHtmlElementById("eta_download");
// Get the Download Page????
HtmlPage page3 = ETButton.click();
UnexpectedPage download_ET = new UnexpectedPage(page3.getWebResponse(), page3.getEnclosingWindow());
// Get the Stream
GZIPInputStream in_ET = (GZIPInputStream) download_ET.getWebResponse().getContentAsStream();
// Try writing the stream (to standard out for now)
try
{
byte[] buffer = new byte[2048];
int len;
while((len = in_ET.read(buffer)) != -1)
{
System.out.write(buffer, 0, len);
}
}
finally
{
// Close the stream
in_ET.close();
}
// just do one till this works
break;
}
}
這是一個不錯的開始:)我在單擊按鈕時查看了正在發送的請求:
如您所見,有幾個參數正在發送(緯度,經度,date_end,image_id)。 在響應中,您具有下載URL。 這個請求是用一些Javascript代碼生成的,可能是這樣的:
function downloadImage(divName,urlProduct){
$(document).ready(function(){
$(divName).on('click', function(){
onlyshowLoading();
$.ajax({
url: urlProduct,
type: "POST",
data: JSON.stringify({
"lat": $('#latitude').val(),
"lng": $('#longitude').val(),
"date_info": $('#date_start').val() + ' to ' + $('#date_end').val(),
'image_id': $("#dropdown:first-child").text().split(" / ")[1],
}),
dataType: 'json',
cache: true,
error: function(){
AjaxOnError();
},
success: function(data){
AjaxOnSuccess();
if (typeof ETa_adjusted == "undefined" || ETa_adjusted == null){
$("#ETrF_adjusted").hide();
$("#EToF_adjusted").hide();
$("#ETa_adjusted").hide();
$("#etrF_adj_download").hide();
$("#etoF_adj_download").hide();
$("#eta_adj_download").hide();
} else{
$("#ETrF_adjusted").show();
$("#EToF_adjusted").show();
$("#ETa_adjusted").show();
$("#etrF_adj_download").show();
$("#etoF_adj_download").show();
$("#eta_adj_download").show();
}
var key = Object.keys(data);
typeName = data[key]
window.open(typeName.url, '_blank');
}
});
});
})
}
因此,由於Jquery或其他原因,HtmlUnit可能無法執行此代碼。 您可以創建自己的WebRequest對象,並重現Javascript邏輯,然后將獲得下載URL。
這是一個有趣的主題,如果您想了解更多信息,我正在撰寫有關使用Java進行網絡抓取的電子書: Java Web Scraping Handbook
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.