ダウンロード方法がわからないファイル以上HTTP Pythonを使用した?
質問
私は小さいできるユーティリティを使っているダウンロードでMP3のウェブサイトからのスケジュール、そしてデザインのポッドキャストをXMLファイルか明らかに追加されiTunesでダウンロードできます。
テキスト処理を生成する/更新のXMLファイルです。使っていwget内窓 .bat
ファイルをダウンロードは実際のMP3しています。しみじみのユPythonで記述されている。
悩んだことなどによるものですが実際にダウンロードファイルのPythonでは、このようなぜんぽ wget
.
なので、ダウンロード方法がわからないファイルをPython?
解決
Python2を使用urllib2付属の標準図書館があります。
import urllib2
response = urllib2.urlopen('http://www.example.com/')
html = response.read()
もっとも基本的な使い方を、図書館、マイナス誤ります。することができまより複雑なもの変更などができます。書類につきま こちらです。
他のヒント
つまり、 urlretrieve
:
import urllib
urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
(Python3+の利用 import urllib.request
や urllib.request.urlretrieve
)
の一部は、"progressbar"
import urllib2
url = "http://download.thinkbroadband.com/10MB.zip"
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,
f.close()
2012年の利用 pythonの要求図書館
>>> import requests
>>>
>>> url = "http://download.thinkbroadband.com/10MB.zip"
>>> r = requests.get(url)
>>> print len(r.content)
10485760
実行可能です pip install requests
っておきたいところです。
ご要望には多くのメリットの選択肢ので、APIはより簡単になります。これは特に、trueの場合にだけ認証を行います。urllibとurllib2っunintuitiveいます。
2015-12-30
人の表現と感動の進捗バーがあります。でっていくのか。あの解決を行う tqdm
:
from tqdm import tqdm
import requests
url = "http://download.thinkbroadband.com/10MB.zip"
response = requests.get(url, stream=True)
with open("10MB", "wb") as handle:
for data in tqdm(response.iter_content()):
handle.write(data)
この実施@kvanceに記載の30ヶ月前。
import urllib2
mp3file = urllib2.urlopen("http://www.example.com/songs/mp3.mp3")
with open('test.mp3','wb') as output:
output.write(mp3file.read())
の wb
に open('test.mp3','wb')
開くファイルおよび消去、既存のファイルのバイナリモードできますのでデータを保存しれない。
Python3
-
import urllib.request response = urllib.request.urlopen('http://www.example.com/') html = response.read()
-
import urllib.request urllib.request.urlretrieve('http://www.example.com/songs/mp3.mp3', 'mp3.mp3')
Python2
urllib2.urlopen
(感謝 アルテミーシア湖)import urllib2 response = urllib2.urlopen('http://www.example.com/') html = response.read()
urllib.urlretrieve
(感謝 PabloG)import urllib urllib.urlretrieve('http://www.example.com/songs/mp3.mp3', 'mp3.mp3')
利用wgetモジュール:
import wget
wget.download('url')
の改良版PabloGコードをPython2/3:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import ( division, absolute_import, print_function, unicode_literals )
import sys, os, tempfile, logging
if sys.version_info >= (3,):
import urllib.request as urllib2
import urllib.parse as urlparse
else:
import urllib2
import urlparse
def download_file(url, dest=None):
"""
Download and save a file specified by url to dest directory,
"""
u = urllib2.urlopen(url)
scheme, netloc, path, query, fragment = urlparse.urlsplit(url)
filename = os.path.basename(path)
if not filename:
filename = 'downloaded.file'
if dest:
filename = os.path.join(dest, filename)
with open(filename, 'wb') as f:
meta = u.info()
meta_func = meta.getheaders if hasattr(meta, 'getheaders') else meta.get_all
meta_length = meta_func("Content-Length")
file_size = None
if meta_length:
file_size = int(meta_length[0])
print("Downloading: {0} Bytes: {1}".format(url, file_size))
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = "{0:16}".format(file_size_dl)
if file_size:
status += " [{0:6.2f}%]".format(file_size_dl * 100 / file_size)
status += chr(13)
print(status, end="")
print()
return filename
if __name__ == "__main__": # Only run if this file is called directly
print("Testing with 10MB download")
url = "http://download.thinkbroadband.com/10MB.zip"
filename = download_file(url)
print(filename)
簡単ない Python 2 & Python 3
対応方法が six
図書館
from six.moves import urllib
urllib.request.urlretrieve("http://www.example.com/songs/mp3.mp3", "mp3.mp3")
同意したアルテミーシア湖,urllib2はよりも urllib とあるモジュールを使いたいのであれば複雑な"とんとことって~えいとくの回答をより完全urllibは簡単なモジュールしたい場合は、基本機能:
import urllib
response = urllib.urlopen('http://www.example.com/sound.mp3')
mp3 = response.read()
ありません。または、行わない場合は、"応答"オブジェクトで呼び read() 直接:
import urllib
mp3 = urllib.urlopen('http://www.example.com/sound.mp3').read()
以下に、最も一般的に使用話をダウンロードファイルは、pythonにおけ
urllib.urlretrieve ('url_to_file', file_name)
urllib2.urlopen('url_to_file')
requests.get(url)
wget.download('url', file_name)
注意: urlopen
や urlretrieve
見を行う比較的悪ダウンロードしたファイルサイズ>500MB). requests.get
店舗のファイルをメモリまでダウンロードが完了します。
import os,requests
def download(url):
get_response = requests.get(url,stream=True)
file_name = url.split("/")[-1]
with open(file_name, 'wb') as f:
for chunk in get_response.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
download("https://example.com/example.jpg")
を得ることができ進展によるフィードバックurlretrieveど
def report(blocknr, blocksize, size):
current = blocknr*blocksize
sys.stdout.write("\r{0:.2f}%".format(100.0*current/size))
def downloadFile(url):
print "\n",url
fname = url.split('/')[-1]
print fname
urllib.urlretrieve(url, fname, report)
まwgetを設置し、利用できるparallel_sync.
pipイparallel_sync
from parallel_sync import wget
urls = ['http://something.png', 'http://somthing.tar.gz', 'http://somthing.zip']
wget.download('/tmp', urls)
# or a single file:
wget.download('/tmp', urls[0], filenames='x.zip', extract=True)
メンバーhttps://pythonhosted.org/parallel_sync/pages/examples.html
これがかない。でダウンロードできるファイルを並行して、再入不可能でもダウンロードファイルのリモートマシン。
にpython3できurllib3とshutil libraires.ダウンロードして使用pipはpip3によってかpython3ではデフォルト)
pip3 install urllib3 shutil
そしてこのコード
import urllib.request
import shutil
url = "http://www.somewebsite.com/something.pdf"
output_file = "save_this_name.pdf"
with urllib.request.urlopen(url) as response, open(output_file, 'wb') as out_file:
shutil.copyfileobj(response, out_file)
またダウンロード urllib3
が使用 urllib
コード
場合速に行う小型の性能試験のためのモジュール urllib
や wget
, に関しては、 wget
たと一緒にステータスバーとは一度もあります。また三つの異なる500MB以上の空き容量ファイルのテスト(別のファイルを解消の機会があるとのキャッシング後のフード).動作確認はdebianマシン、python2.
第一に、これらの結果と類似しており異なる運転):
$ python wget_test.py
urlretrive_test : starting
urlretrive_test : 6.56
==============
wget_no_bar_test : starting
wget_no_bar_test : 7.20
==============
wget_with_bar_test : starting
100% [......................................................................] 541335552 / 541335552
wget_with_bar_test : 50.49
==============
を行っていましたが、試験の"プロファイル"デコレータ.このフルコード:
import wget
import urllib
import time
from functools import wraps
def profile(func):
@wraps(func)
def inner(*args):
print func.__name__, ": starting"
start = time.time()
ret = func(*args)
end = time.time()
print func.__name__, ": {:.2f}".format(end - start)
return ret
return inner
url1 = 'http://host.com/500a.iso'
url2 = 'http://host.com/500b.iso'
url3 = 'http://host.com/500c.iso'
def do_nothing(*args):
pass
@profile
def urlretrive_test(url):
return urllib.urlretrieve(url)
@profile
def wget_no_bar_test(url):
return wget.download(url, out='/tmp/', bar=do_nothing)
@profile
def wget_with_bar_test(url):
return wget.download(url, out='/tmp/')
urlretrive_test(url1)
print '=============='
time.sleep(1)
wget_no_bar_test(url2)
print '=============='
time.sleep(1)
wget_with_bar_test(url3)
print '=============='
time.sleep(1)
urllib
そうすると最速の
の完全性、また呼び出すことはできずプログラム検索ファイルを使用 subprocess
パッケージです。プログラム専用の検索ファイルによPythonのような機能 urlretrieve
.例えば、 wget
ダウンロードできるディレクトリを再帰的に(-R
とができ、対応FTP、リダイレクト、HTTPプロキシで避ける再ダウンロードで既存のファイル-nc
) aria2
できるマルチ接続のダウンロード可能性のあるスピードをダウンロード
import subprocess
subprocess.check_output(['wget', '-O', 'example_output_file.html', 'https://example.com'])
にJupyterノートでも、プログラムに直接 !
構文:
!wget -O example_output_file.html https://example.com
ソースコード:
import urllib
sock = urllib.urlopen("http://diveintopython.org/")
htmlSource = sock.read()
sock.close()
print htmlSource
私は以下のように書いている作品にバニラビーンズPython2はPython3.
import sys
try:
import urllib.request
python3 = True
except ImportError:
import urllib2
python3 = False
def progress_callback_simple(downloaded,total):
sys.stdout.write(
"\r" +
(len(str(total))-len(str(downloaded)))*" " + str(downloaded) + "/%d"%total +
" [%3.2f%%]"%(100.0*float(downloaded)/float(total))
)
sys.stdout.flush()
def download(srcurl, dstfilepath, progress_callback=None, block_size=8192):
def _download_helper(response, out_file, file_size):
if progress_callback!=None: progress_callback(0,file_size)
if block_size == None:
buffer = response.read()
out_file.write(buffer)
if progress_callback!=None: progress_callback(file_size,file_size)
else:
file_size_dl = 0
while True:
buffer = response.read(block_size)
if not buffer: break
file_size_dl += len(buffer)
out_file.write(buffer)
if progress_callback!=None: progress_callback(file_size_dl,file_size)
with open(dstfilepath,"wb") as out_file:
if python3:
with urllib.request.urlopen(srcurl) as response:
file_size = int(response.getheader("Content-Length"))
_download_helper(response,out_file,file_size)
else:
response = urllib2.urlopen(srcurl)
meta = response.info()
file_size = int(meta.getheaders("Content-Length")[0])
_download_helper(response,out_file,file_size)
import traceback
try:
download(
"https://geometrian.com/data/programming/projects/glLib/glLib%20Reloaded%200.5.9/0.5.9.zip",
"output.zip",
progress_callback_simple
)
except:
traceback.print_exc()
input()
注記:
- ト"の進捗バーの"コールバック.
- ダウンロードは4MB。zipからです。
利用できる PycURL Python2-3
import pycurl
FILE_DEST = 'pycurl.html'
FILE_SRC = 'http://pycurl.io/'
with open(FILE_DEST, 'wb') as f:
c = pycurl.Curl()
c.setopt(c.URL, FILE_SRC)
c.setopt(c.WRITEDATA, f)
c.perform()
c.close()
このちょっと遅くなっpabloGのコードと、思えます。システム('clsで見!チェックアウト:
import urllib2,os
url = "http://download.thinkbroadband.com/10MB.zip"
file_name = url.split('/')[-1]
u = urllib2.urlopen(url)
f = open(file_name, 'wb')
meta = u.info()
file_size = int(meta.getheaders("Content-Length")[0])
print "Downloading: %s Bytes: %s" % (file_name, file_size)
os.system('cls')
file_size_dl = 0
block_sz = 8192
while True:
buffer = u.read(block_sz)
if not buffer:
break
file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,
f.close()
場環境で動作以外のWindowsを使うその他その後'cls.MAC OS XやLinuxのであることから'.
urlretrieveます。の取得は簡単に、しかし、現実にはいません。私は取得データのためのカップルサイトを含むテキストや画像のう解決の多くは事ができます。がよりユニバーサル溶液からの利用urlopen.として行っていくことをPython3に標準ライブラリは、コードが実機をPython3以外のブラウザはご利用にならなインストールサイト-パッケージ
import urllib.request
url_request = urllib.request.Request(url, headers=headers)
url_connect = urllib.request.urlopen(url_request)
#remember to open file in bytes mode
with open(filename, 'wb') as f:
while True:
buffer = url_connect.read(buffer_size)
if not buffer: break
#an integer value of size of written data
data_wrote = f.write(buffer)
#you could probably use with-open-as manner
url_connect.close()
この答えするソリューションを提供HTTP403Forbiddenをダウンロードする場合は、ファイルはhttpを用います。しかし以外の方法での要望は受け付けならびurllibモジュール、その他のモジュールがあるものを提供し、より良いものですが、私が最も気に入っていを解決するために用いられものです。