Ways to download files in Python

Source: Internet
Author: User

The previous time is crawling text, recently ready to crawl pictures

Two ways to save files have been found

One is to use the Urllib.urlretrieve method

#-*-coding:utf-8-*-import urllibdef callbackfunc (Blocknum, BlockSize, totalsize):    "' Callback function    @blocknum: Data Block    @blocksize: The size of the data block    @totalsize: The size of the remote file    "'    percent = 100.0 * Blocknum * blocksize/totalsize< C7/>if percent >:        percent =    #格式化输出,% equivalent to escape    print "%.2f%%"% percent#local = ' d:\\sina.html ' # Urllib.urlretrieve (URL, local, callbackfunc)

This callback function is quite convenient, in the next large file, you can visually see the download situation

Another is to use the open and write methods to download

#-*-coding:utf-8-*-import urllibimport osurl = ' http://pic10.nipic.com/20101014/3367900_101327028816_2.jpg ' # Urllib.urlretrieve (URL, local, callbackfunc) u=urllib.urlopen (URL) data=u.read () filename= "123.jpg" # Select Images Directory Os.chdir ("Images") f =open (FileName, ' WB ') f.write (data) print U "Download", Filenamef.close ()

Ways to download files in Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.