본문 바로가기

수업정리/Fundamental

[Python] 한글 유니코드 9 - urllib.py, scrape_wiki_random.py, 위키에서 읽고 데이터 받기?

 wget http://www.py4e.com/code3/socket1.py    :   소켓은 통신을 위한 객체로 데이터를 주고 받을 수 있다. 예제 파일 다운

python socket1.py    :   예제 파일 실행

wget https://www.py4e.com/code3/urllib1.py     :  urllib1.py 파일은 urllib 라이브러리를 사용하여 웹 페이지를 가져오고 출력하는 예제 코드입니다. urllib 모듈을 사용하여 웹 요청을 수행하고, 서버에서 받은 응답을 처리하여 웹 페이지의 내용을 출력할 것입니다.

python urllib1.py   :  예제 파일 실행

urllib2.py

 import urllib.request

 fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
 print('url request handler', fhand)
 for line in fhand:
     #print(line.decode().strip())
     print('no decode()', line.strip())
~

decode 를 하면 b'str' 이 str 로 된다. 이는 (byte) 타입에서 (str) 타입으로 바뀐다.


str_bytes.py

bytestr = b'Hi Korea!'  # bytes는 0~255에 속하는 ASCII 문자만 포함할 수 있습니다.
# bytestr = b'ō to| 12|ot' # 작동하지 않습니다. 코드 포인트가 0~255 범위에 속하지 않기 때문입니다.
# 오히려, 멀티 바이트 코드 포인트의 각 바이트를 'utf-8'로 지정하여 bytes()로 표현할 수 있습니다.
print(bytes('하이', 'utf-8', 'ignore'))
bytestr = bytes('하이', 'utf-8', 'ignore')
print(bytestr)
print(type(bytestr))
# bytes를 문자열로 디코딩합니다.
result = bytestr.decode('utf-8')
print('decode:', result)
print(type(result))

주어진 문자열을 바이트로 변환하고, 변환된 바이트를 다시 문자열로 디코딩하여 결과를 출력합니다


urlrequest.py ( urllib1.py 와 동일 )

 import requests

 r = requests.get('http://data.pr4e.org/romeo.txt')
 print(r.text)

조금 더 쉽게 읽을 수 있게 만든 것이다.

 


scrape_wiki_random.py

 #code:utf-8
 from crawl_wiki import find_first_link, continue_crawl

 #main
 import time
 import urllib.parse # to decode any URL string

 start_url = "https://en.wikipedia.org/wiki/Special:Random"
 target_url = "https://en.wikipedia.org/wiki/한글"
 input('start:%s' %start_url)
 input('target:%s' %target_url)

 article_chain = [start_url]

 while continue_crawl(article_chain, target_url):
     print('current last', article_chain[-1])
     print(urllib.parse.unquote(article_chain[-1])) # to decode url string

     first_link = find_first_link(article_chain[-1])
     if not first_link:
         print("We've arrived at an article with no links, aborting search!")
         break

     article_chain.append(first_link) # Update the last url
     time.sleep(2) # Slow things down so as to not hammer Wikipedia's servers

위 코드는 한국어로 된 위키피디아 문서를 탐색하는 프로그램입니다. 

시작 URL에서 시작하여 링크를 따라 이동하면서 목표 URL에 도달하거나 일정 조건에 도달할 때까지 탐색을 진행합니다.

코드의 구성은 다음과 같습니다:

시작 URL과 목표 URL을 설정합니다.
article_chain 리스트를 시작 URL로 초기화합니다.
continue_crawl 함수를 사용하여 탐색을 진행할지 여부를 판단합니다.
article_chain의 마지막 URL이 목표 URL에 도달한 경우 탐색을 종료합니다.
article_chain의 길이가 일정 조건을 초과한 경우 탐색을 중단합니다.
article_chain에 이미 방문한 URL이 있는 경우 탐색을 중단합니다.
탐색을 진행하는 동안 현재 마지막 URL을 출력합니다.
URL을 디코드하여 출력합니다.
find_first_link 함수를 사용하여 현재 마지막 URL에서 첫 번째 링크를 찾습니다.
첫 번째 링크가 없는 경우 탐색을 중단합니다.
article_chain에 첫 번째 링크를 추가하여 다음 URL로 이동합니다.
일정 시간(2초)을 기다린 후 다음 탐색을 진행합니다.
위 코드는 한국어로 된 위키피디아 문서를 탐색하는 기능을 수행합니다. 시작 URL과 목표 URL을 설정한 후 코드를 실행하면 탐색 과정을 확인할 수 있습니다.