본문 바로가기
개념/혼자 공부하는 파이썬

python) Downloading and Saving Content from the Web with Python

by kiseno 2024. 11. 20.
728x90
반응형
SMALL
from urllib import request

target = request.urlopen("http url")
output = target.read()
print(output)

file = open("output.png", "wb")
file.write(output)
file.close()

1. **from urllib import request**: Imports the `request` submodule from Python's `urllib` module. `urllib` is a package that contains several modules for working with URLs, and `request` is specifically used for opening and reading URLs.

2. **target = request.urlopen("http url")**: Opens the URL given as "http url" and assigns the opened URL object to the variable `target`. This object allows operations like reading from the URL.

3. **output = target.read()**: Reads the entire content of the file pointed to by the URL and stores it in the variable `output`. This content is in binary format, suitable for binary files like images, videos, etc.

4. **print(output)**: Prints the binary content of the downloaded file. In practical use, this might not be very informative for binary data and is more useful for debugging purposes or when dealing with text data.

5. **file = open("output.png", "wb")**: Opens a file named `output.png` in binary write mode (`"wb"`). If `output.png` does not exist, it will be created; if it does exist, it will be overwritten. The opened file is referred to by the variable `file`.

6. **file.write(output)**: Writes the binary content stored in `output` to the file associated with `file`. This action effectively saves the downloaded content to a file on the local filesystem.

7. **file.close()**: Closes the file, ensuring that all the written content is properly saved and that system resources are released.

728x90
반응형
LIST