2011-08-30 7 views
167

私は、同じゲーム/アプリケーションの.jadファイルで指定されたURLを読んで、Webサーバーから.jar(java)ファイルをダウンロードするプログラムを作成しています。私はPython 3.2.1を使用していますWebからPython 3のファイルをダウンロード

私はJADファイルからJARファイルのURLを抽出することができました(すべてのJADファイルにはJARファイルのURLが含まれています)が、あなたが想像しているように、 type()の文字列です。

はここに関連する機能です:私は常に関数内のタイプは、上記のバイトではなく文字列である必要がありますというエラーを取得するしかし

def downloadFile(URL=None): 
    import httplib2 
    h = httplib2.Http(".cache") 
    resp, content = h.request(URL, "GET") 
    return content 

downloadFile(URL_from_file) 

。私はURL.encode( 'utf-8')とバイト(URL、encoding = 'utf-8')を使用してみましたが、常に同じか類似のエラーが発生します。

URLは文字列型で格納されているので、基本的に私の質問は、サーバーからファイルをダウンロードする方法です。

+3

@alvas、これに対する賞金?回答者はまだSO上で(そしてかなり)活発です。単にコメントを追加して尋ねるのはなぜですか? –

+2

Cos時間のテストに耐えられる良い答えは、価値のあるものです。また、今日の回答が適切かどうかを確認するために、これを他の多くの質問で開始する必要があります。特にSOの回答のソートがかなり狂っているときは、時代遅れの、あるいは最悪の回答がトップになることがあります。 – alvas

答えて

353

あなたは、変数に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) 

urlretrievelegacyとみなされ、廃止される可能性があります(理由はわかりません)。

だから、これを行うには最も正しいの方法は、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`. 
+7

'Content-Type'ヘッダから文字エンコーディングを得るために' utf-8'をハードコーディングする代わりに 'response.info()。get_param( 'charset'、 'utf-8')'を使うことができます。 – jfs

+2

@OlehPrypinなぜですか'outfile.write(data)'は小さなファイルに対してのみうまく動作しますか? – Startec

+0

「urlretrieveは遺産とみなされ、廃止される可能性があります。 –

11

私はある質問右、理解を願って:URLは文字列型に格納されているサーバーからファイルをダウンロードする方法を?

私は、ファイルをダウンロードし、以下のコード使用してローカルに保存します:そのAPIで始まるのは非常に簡単ですので、私はHTTPリクエストに関連する何かをしたい時はいつでも、私はrequestsパッケージを使用

import requests 

url = 'https://www.python.org/static/img/python-logo.png' 
fileName = 'D:\Python\dwnldPythonLogo.png' 
req = requests.get(url) 
file = open(fileName, 'wb') 
for chunk in req.iter_content(100000): 
    file.write(chunk) 
file.close() 
+0

こんにちは、ファイルのダウンロードにも同じタイプのコードを使用していますが、「charmap」コーデックでは「\ u010c」というエンコードはできません。最初のインストール要求に言及するために、 – Joyson

51

を:最初の

requests

$ pip install requests 

をインストールし、その後コード:

from requests import get # to make GET request 


def download(url, file_name): 
    # open in binary mode 
    with open(file_name, "wb") as file: 
     # get request 
     response = get(url) 
     # write to file 
     file.write(response.content) 
+29

+1を手伝ってください。 この種の文化は、stackoverflowで行われるべきであり、近隣のサイトは、情報のすべてのビットが間違っていることを視聴者が知っていると仮定します。 – TechJS

-2
from urllib import request 

def get(url): 
    with request.urlopen(url) as r: 
     return r.read() 


def download(url, file=None): 
    if not file: 
     file = url.split('/')[-1] 
    with open(file, 'wb') as f: 
     f.write(get(url)) 
0

あなたはそのための人気のダウンロード・シェル・ツールですwgetのを使用することができます。 https://pypi.python.org/pypi/wget これは、宛先ファイルを開く必要がないため、最も簡単な方法です。ここに例があります。

import wget 
url = 'https://i1.wp.com/python3.codes/wp-content/uploads/2015/06/Python3-powered.png?fit=650%2C350' 
wget.download(url, '/Users/scott/Downloads/cat4.jpg')