urllib를 이용해 웹 데이터 읽어오기

매일 공부(ML)·2022년 2월 24일
0

urllib 라이브러리

urllib을 활용하면 아주 간단하게 웹 브라우저를 만들 수 있습니다.

이전에 여러 줄에 걸쳐 만들었던 웹 브라우저가 urllib 라이브러리를 활용하면 이렇게 4줄만에 완성이 됩니다.

import urllib.request, urllib.parse, urllib.error

fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
for line in fhand:
    print(line.decode().strip())

이것을 응용하면 이전에 파일에서 데이터를 읽어왔던 것을 인터넷에서 데이터를 읽어올 수 있습니다.

import urllib.request, urllib.parse, urllib.error

fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')

counts = dict()
for line in fhand:
    words = line.decode().split()
    for word in words:
        counts[word] = counts.get(word, 0) + 1
print(counts)
 

그리고 이렇게 HTML로 만들어진 웹 페이지도 읽어올 수 있습니다.

import urllib.request, urllib.parse, urllib.error

fhand = urllib.request.urlopen('http://www.dr-chuck.com/page1.htm')
for line in fhand:
    print(line.decode().strip())

웹 페이지에서 읽어온 데이터는 HTML 형태

profile
성장을 도울 아카이빙 블로그

0개의 댓글