あなたは、変数にurllib.request.urlopen
のちょうどread
応答をWebページの内容を取得したい場合:
import urllib.request
...
url = 'http://example.com/'
response = urllib.request.urlopen(url)
data = response.read() # a `bytes` object
text = data.decode('utf-8') # a `str`; this step can't be used if data is binary
ファイルをダウンロードし、保存するための最も簡単な方法は、urllib.request.urlretrieve
を使用することです機能:
import urllib.request
...
# Download the file from `url` and save it locally under `file_name`:
urllib.request.urlretrieve(url, file_name)
import urllib.request
...
# Download the file from `url`, save it in a temporary directory and get the
# path to it (e.g. '/tmp/tmpb48zma.txt') in the `file_name` variable:
file_name, headers = urllib.request.urlretrieve(url)
urlretrieve
はlegacyとみなされ、廃止される可能性があります(理由はわかりません)。
だから、これを行うには最も正しいの方法は、HTTPレスポンスを表し、shutil.copyfileobj
を使用して実際のファイルにコピーしたファイルのようなオブジェクトを返すようにurllib.request.urlopen
機能を使用することです。
import urllib.request
import shutil
...
# Download the file from `url` and save it locally under `file_name`:
with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file:
shutil.copyfileobj(response, out_file)
これは複雑すぎると思われる場合は、単純に行くとbytes
オブジェクト全体のダウンロードを保存して、ファイルに書きたいことがあります。しかし、これは小さなファイルに対してのみうまくいきます。
import urllib.request
...
# Download the file from `url` and save it locally under `file_name`:
with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file:
data = response.read() # a `bytes` object
out_file.write(data)
オンザフライで圧縮されたデータを.gz
(そしておそらく他のフォーマット)を抽出することが可能であるが、そのような操作は、おそらくファイルへのランダムアクセスをサポートするためのHTTPサーバが必要です。
import urllib.request
import gzip
...
# Read the first 64 bytes of the file inside the .gz archive located at `url`
url = 'http://example.com/something.gz'
with urllib.request.urlopen(url) as response:
with gzip.GzipFile(fileobj=response) as uncompressed:
file_header = uncompressed.read(64) # a `bytes` object
# Or do anything shown above using `uncompressed` instead of `response`.
@alvas、これに対する賞金?回答者はまだSO上で(そしてかなり)活発です。単にコメントを追加して尋ねるのはなぜですか? –
Cos時間のテストに耐えられる良い答えは、価値のあるものです。また、今日の回答が適切かどうかを確認するために、これを他の多くの質問で開始する必要があります。特にSOの回答のソートがかなり狂っているときは、時代遅れの、あるいは最悪の回答がトップになることがあります。 – alvas