Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
723 views
in Technique[技术] by (71.8m points)

Wait for Download to finish in selenium webdriver JAVA

Once clicking a download button, files will be downloaded. Before executing next code, it needs to wait until the download completes.

My code looks like this:

Thread.sleep(2000);
driver.findElement(By.xpath("//*[@id='perform']")).click();//click for download

Thread.sleep(20000);
//code to be executed after download completes
Readfile fileobj=new Readfile();
String checkfile=fileobj.checkfilename();

How can I make the webdriver wait until a download completes?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A little late but this question has a good number of views, I thought it would be worth the time to answer it in case you haven't moved on or someone else comes across it.

I too ran into the same problem and thought I'd share. I was developing in python at the time but the same concept applies. You don't have to do the actual download using selenium. Rather than clicking on the element to start the download, you should consider retrieving the link and using built in functions to proceed from there.

The element you would normally click to begin the download should have a 'href' attribute that you should be able to read using selenium. This is the url pointing to the actual file. In python, it looks something like this:

    element = driver.find_element_by_id('dl_link')
    url = element.get_attribute('href')

From here you can use an http library to call the url. The important part here is that you set 'stream' to true so you can begin writing the bytes to a file. Make sure the file path contains the correct file extension and another thing, most operating systems don't allow you to name files with certain characters such as back slashes or quotations so heads up on that.

def download_file(url, file_path):
    from requests import get
    reply = get(url, stream=True)
    with open(file_path, 'wb') as file:
        for chunk in reply.iter_content(chunk_size=1024): 
            if chunk:
                file.write(chunk)

The program shouldn't continue until the download is complete making it no longer necessary to poll until it is complete.

I apologize for answering in a different language, in Java I believe you can use the HttpURLConnection API. Hope this helps!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...