파싱은 구문 분석이라는 뜻인데 웹 페이지 파싱은 주로 웹 페이지에 나와 있는 여러 정보를 필요한 것만 가져와서 사용하는 것이다.
예를 들어 버스가 몇 분 후에 도착한다는 것을 알려주는 웹 페이지가 있다고 하자. 우린 그 페이지에서 버스가 오는 예상 시간만 가져와서 처리하는 프로그램을 만든다고 했을 때, 그 웹 페이지에서 정보를 가져와 시간만 건져내는 게 파싱이라고 생각하면 된다.
자 그럼 파싱을 하는 프로그램을 만들려면 웹 페이지를 가져오는 기능과 가져온 웹페이지를 가공하는 두 가지 기능이 필요하다.
먼저 웹 페이지를 가져오는 기능을 만들기 위해 Python에서 'requests'라는 라이브러리를 써야 한다. 기본으로 탑재되어있지 않을 테니 내려받자. 라이브러리를 내려받기 위해선 cmd에서 다음 명령어를 입력하자. (오류가 나면 관리자 권한으로도 실행 해보자)
pip3 install requests
설치가 완료되었다면, Python command line을 실행시켜 다음 명령어를 입력해보자. URL에 자기가 원하는 링크를 넣으면 된다.
>>> import requests
>>> response = requests.get(URL)
>>> print(response.text)
덧. URL에 http:// 나 https:// 를 안 붙이면 다음과 같은 오류가 난다. 또 잘못된 주소일 경우도 오류가 난다.
명령이 성공적으로 수행되었다면 웹 페이지의 HTML이 보여진다.
requests에 대한 설명이 어느 정도 된 것 같으니 코드로 넘어가서 두 번째 기능도 설명하겠다.
import requests
while(1): # URL
try:
URL = input("Insert URL: ")
if(URL not in ['http://', 'https://']):
URL = 'http://' + URL # 편의를 위해 'http://'자동입력
response = requests.get(URL)
text = response.text
break
except:
print("Did you insert correct one?")
continue
while(1): # option
try:
option = int(input("Want parse with parameter or without parameter? (with : 0 / without : 1): "))
if(option not in [0, 1]):
print("0 or 1 plz")
continue
break
except:
print("Number 0 or 1!")
continue
while(1): # first parameter
first = input("Input first parameter: ")
if(not(first in text)):
print("First one not founded!")
continue
if(text.count(first) >= 2):
check = input("I found first parameter at least two want to input again? (Y/N)").lower()
if(check == 'n'):
break
elif(check == 'y'):
continue
else:
print("well.. just go")
continue
break
while(1): # last parameter
last = input("Input last parameter: ")
if(not(last in text[text.index(first) + len(first):])):
print("No parameter founded!")
continue
if(text.count(last) >= 2):
check = input("I found last parameter at least two want to input again? (Y/N)").lower()
if(check == 'n'):
break
elif(check == 'y'):
continue
else:
print("well.. just go")
continue
break
text = text[text.index(first):]
if(option == 0): # with
print(text[:text[len(first):].index(last) + len(last) + len(first)])
elif(option == 1): # without
print(text[len(first):text[len(first):].index(last) + len(first)])
맨 마지막 print구문은 조금 복잡한데, 첫 구문을 입력하고 마지막 구문을 입력할 때, 첫 구문에서 검색하는 걸 제외하도록 만들었다.
이걸로 블로그 조회수를 파싱해보자.
오늘 조회수는 <span class="head">Today</span><span class="hit"> 와 </span>사이에 있다.
성공적으로 파싱이 되었다.
'Programming > Algorithm' 카테고리의 다른 글
[Python3] 대칭수찾기2 (2) | 2017.02.25 |
---|---|
[Python3] 맞춤법 검사기 (1) | 2017.02.13 |
[Python3] 3 6 9 게임 (0) | 2017.01.22 |
[Python3] BruteList (0) | 2017.01.04 |
[Python3] 대칭수찾기 (0) | 2016.12.28 |