Python 3에서 웹에서 파일 다운로드
같은 게임/응용프로그램의 .jad 파일에 지정된 URL을 읽어 웹서버에서 .jar(java) 파일을 다운로드하는 프로그램을 만들고 있다.나는 Python 3.2.1을 사용하고 있다.
JAD 파일(모든 JAD 파일에는 JAR 파일의 URL이 포함되어 있다)에서 JAR 파일의 URL을 추출해 냈지만, 짐작하시겠지만 추출된 값은 유형() 문자열이다.
관련 기능:
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이 문자열 유형으로 저장되었을 때 서버에서 파일을 다운로드하는 방법인가?
웹 페이지의 내용을 변수로 가져오려면read
의 응답:
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
파일을 다운로드하고 저장하는 가장 쉬운 방법은 다음 기능을 사용하는 것이다.
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
유산으로 간주되며, 더 이상 사용되지 않을 수 있다(그러나, 그 이유는 확실하지 않다.
따라서 가장 정확한 방법은 함수를 사용하여 HTTP 응답을 나타내는 파일 형식의 개체를 반환하고 를 사용하여 실제 파일에 복사하는 것이다.
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`.
나는 사용한다requests
HTTP 요청과 관련된 항목을 원할 때마다 패키지를 만드는 이유는 API가 다음과 같이 쉽게 시작할 수 있기 때문에
먼저, 설치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)
URL이 문자열 유형으로 저장되어 있을 때 서버에서 파일을 다운로드하는 방법이라는 질문을 제대로 이해했으면 좋겠다.
아래 코드를 사용하여 파일을 다운로드하고 로컬로 저장한다.
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()
여기서 urllib의 Legacy 인터페이스를 Python3:
다음 기능 및 클래스는 Python 2 모듈 urllib에서 포팅된다(urllib2와는 반대로).그들은 미래의 어느 시점에서 더 이상 사용되지 않을 수도 있다.
예제(2줄 코드):
import urllib.request
url = 'https://www.python.org/static/img/python-logo.png'
urllib.request.urlretrieve(url, "logo.png")
당신은 그것을 위해 인기있는 셸 툴인 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')
그렇다, 확실한 요청은 HTTP 요청과 관련된 어떤 것에 사용하기 좋은 패키지다.그러나 우리는 수신 데이터의 인코딩 유형에 주의할 필요가 있고 아래도 그 차이를 설명하는 예다.
from requests import get
# case when the response is byte array
url = 'some_image_url'
response = get(url)
with open('output', 'wb') as file:
file.write(response.content)
# case when the response is text
# Here unlikely if the reponse content is of type **iso-8859-1** we will have to override the response encoding
url = 'some_page_url'
response = get(url)
# override encoding by real educated guess as provided by chardet
r.encoding = r.apparent_encoding
with open('output', 'w', encoding='utf-8') as file:
file.write(response.content)
당신이 리눅스를 할 수 .wget
파이톤 셸을 통해 리눅스의 모듈.여기 샘플 코드 조각이 있다.
import os
url = 'http://www.example.com/foo.zip'
os.system('wget %s'%url)
동기
때때로, 우리는 사진을 얻고 싶지만, 그것을 실제 파일로 다운로드 할 필요는 없다.
즉, 데이터를 다운로드하여 메모리에 보관하십시오.
예를 들어 기계학습법을 사용할 경우 숫자(바코드)로 이미지를 인식할 수 있는 모델을 교육하십시오.
내가 몇몇 웹사이트들을 거미줄처럼 꾸미고 그 이미지들을 가지고 있어서 그것을 인식하기 위해 모델을 사용할 수 있을 때,
그 사진들을 내 디스크 드라이브에 저장하기 싫어서
그러면 당신은 당신이 데이터를 메모리에 계속 다운로드 할 수 있도록 하기 위해 아래의 방법을 시도할 수 있다.
포인트
import requests
from io import BytesIO
response = requests.get(url)
with BytesIO as io_obj:
for chunk in response.iter_content(chunk_size=4096):
io_obj.write(chunk)
기본적으로 @Ranvijay Kumar에게
예
import requests
from typing import NewType, TypeVar
from io import StringIO, BytesIO
import matplotlib.pyplot as plt
import imageio
URL = NewType('URL', str)
T_IO = TypeVar('T_IO', StringIO, BytesIO)
def download_and_keep_on_memory(url: URL, headers=None, timeout=None, **option) -> T_IO:
chunk_size = option.get('chunk_size', 4096) # default 4KB
max_size = 1024 ** 2 * option.get('max_size', -1) # MB, default will ignore.
response = requests.get(url, headers=headers, timeout=timeout)
if response.status_code != 200:
raise requests.ConnectionError(f'{response.status_code}')
instance_io = StringIO if isinstance(next(response.iter_content(chunk_size=1)), str) else BytesIO
io_obj = instance_io()
cur_size = 0
for chunk in response.iter_content(chunk_size=chunk_size):
cur_size += chunk_size
if 0 < max_size < cur_size:
break
io_obj.write(chunk)
io_obj.seek(0)
""" save it to real file.
with open('temp.png', mode='wb') as out_f:
out_f.write(io_obj.read())
"""
return io_obj
def main():
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'Accept-Encoding': 'gzip, deflate',
'Accept-Language': 'zh-TW,zh;q=0.9,en-US;q=0.8,en;q=0.7',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Host': 'statics.591.com.tw',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36'
}
io_img = download_and_keep_on_memory(URL('http://statics.591.com.tw/tools/showPhone.php?info_data=rLsGZe4U%2FbphHOimi2PT%2FhxTPqI&type=rLEFMu4XrrpgEw'),
headers, # You may need this. Otherwise, some websites will send the 404 error to you.
max_size=4) # max loading < 4MB
with io_img:
plt.rc('axes.spines', top=False, bottom=False, left=False, right=False)
plt.rc(('xtick', 'ytick'), color=(1, 1, 1, 0)) # same of plt.axis('off')
plt.imshow(imageio.imread(io_img, as_gray=False, pilmode="RGB"))
plt.show()
if __name__ == '__main__':
main()
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))
참조URL: https://stackoverflow.com/questions/7243750/download-file-from-web-in-python-3
'IT이야기' 카테고리의 다른 글
대/소문자를 구분하지 않는 문자열 비교 방법 (0) | 2022.04.04 |
---|---|
Vue.js에서 생성된 이벤트와 마운트된 이벤트 간의 차이 (0) | 2022.04.04 |
왜 && 오퍼레이터가 두 번째 피연산자의 유형을 생성하는가? (0) | 2022.04.04 |
반응 JS를 사용한 무한 스크롤 (0) | 2022.04.04 |
Python 수퍼()가 TypeError를 발생시킴 (0) | 2022.04.04 |