Skip to content

Instantly share code, notes, and snippets.

@hongdonghyun
Created February 10, 2020 10:32
Show Gist options
  • Save hongdonghyun/7dfc98e8190a097beb86fc24eecf025e to your computer and use it in GitHub Desktop.
Save hongdonghyun/7dfc98e8190a097beb86fc24eecf025e to your computer and use it in GitHub Desktop.
from urllib.request import urlopen
# 아래 첨부한 이미지에서 29 ~ 30번째 줄 코드를 작성한 이유가 궁금합니다.
"""
with문은 파일,네트워크,데이터베이스등의 연결을 열고 with안의 구문이 모두 실행되고나면 자동으로 close를 실행하게 해주는 예약어입니다.
파일을 열었으면 당연히 닫아야 하기 때문에 with문으로 작성되었고
파일의 경로에 해당모드로 열겠다 라는 내용이 됩니다.
w는 쓰기모드이며 파일이 없다면 자동으로 생성됩니다.
b는 바이너리파일 모드이며 wb는 바이너파일로 작성하겠다는 내용이됩니다.
바이너리파일은 텍스트의 인코딩이나 줄바꿈문자(\n)에 대한 변환을 하지 않고 1byte단위로 저장하게 됩니다
바이너리파일은 주로 이미지,csv파일을 저장하실때 주로 사용됩니다.
contents에 대한 내용이 이미지 파일과 html파일에 텍스트로 적히는게 가능한지
>>> 이미지파일에 내용을 적는다는게 어떤말인지 잘 모르겠네요.
>>> 제 나름대로 유추해서 이미지를 저장하는 코드를 만들어보았는데 이게 맞나요?
>>> html의 경우 양식만 잘 맞춰서 적어주면 안될건 없어보입니다.
"""
res = urlopen("https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png")
with open("./google.png", "wb") as f:
f.write(res.read())
html = """<!doctype html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
</body>
</html>
"""
with open("./section02-1.html", "w") as f:
f.write(html)
@hongdonghyun
Copy link
Author

hongdonghyun commented Feb 10, 2020

이미지의 경우 request를 보내 데이터를 요청하고 read()를 통해 읽어들이게 되면 이미지를 구성하고 있는 내용이 나옵니다.
이미지라는것 또한 결국에 컴퓨터에 저장될때 문자열의 형태를 취하고 있습니다.
open함수를 통해 컴퓨터에 파일을 read or write를 할땐 확장자까지 다 적어주게 되어있습니다.

    try:
        response = req.urlopen(url)
        contents = response.read()
        print(contents)
        # 여기서 contents를 print해보면 어떠한 내용을 수신했는지 명확하게 알 수 있습니다.
with open(path_list[i], 'wb') as c:
            c.write(contents)

구문을 통해 진행하게 되면 다음과 같은 형식이 되겠죠

with open("D:/crawl-test/test2.jpg", "wb") as c:
    c.write(contents)
    # 이때 contents는 https://search.pstatic.net/common?type=a&size=120x150&quality=95&direct=true&src=http%3A%2F%2Fsstatic.naver.net%2Fpeople%2Fportrait%2F201906%2F20190627094559503.jpg 주소로 요청을 보내면 이미지를 구성하는 문자열을 받습니다.
# 해당내용을 파일명만바꿔서 write하게된다면 이미지가 안 만들어질 이유가 없겠죠?

html의 경우는 더 간단합니다.
확장자만 html로 끝났을 뿐이지 보통의 txt파일과 다른게 없습니다.

http://google.com로 요청을 보내서 요청에 관한 내용물을 수신해옵니다.
수신한 내용은 html을 구성하는 태그와 텍스트가 되겠죠
그러한 내용을 html로 끝나는 파일에 작성하게 되면 해당 파일이 작성되는겁니다.

with open("D:/crawl-test/index2.html", "wb") as c:
    c.write(contents)
    # contents는 http://google.com 여기서 수신한 html코드들이 됩니다.

@coke05288
Copy link

감사합니다! 이해했습니다 ㅠ.ㅠ

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment