웹 크롤링 - 문서 읽기 본문

프로젝트/파이썬

웹 크롤링 - 문서 읽기

뚜스머리 2017. 7. 27. 00:02

웹 크롤러를 제작하면서 단순히 HTML코드뿐 아니라 pdf, txt, csv등 여러 파일을 읽어야 하는 순간이 생기게 된다.


1. 텍스트 파일

사실 텍스트 파일을 직접 올리는 경우는 많지 않다. 그러나 문서만을 다루는 사이트들의 경우 텍스트 파일을 다루는 경우도 종종 있다.

http://doohaproject.tistory.com/22 에 있는 예제 파일을 기준으로 파일을 읽는다면



from urllib.request import urlopen

text = urlopen('http://doohaproject.tistory.com/attachment/cfile2.uf@25A2F43359777C510E95C5.txt')
string = text.read()
print(string)


위의 소스를 실행해보면 파일의 내용을 파이썬 쉘에서 바로 읽을 수 있다.

b'import csv\r\n\r\ncsvFile = open("./test.csv", \'w+\')\r\n\r\ntry:\r\n    writer = csv.writer(csvFile)\r\n    writer.writerow((\'number\', \'number plus 2 \', \'number times 2\'))\r\n    for i in range(10):\r\n        writer.writerow((i, i+2, i*2))\r\nfinally:\r\n    csvFile.close()'



많은 문서의 경우 확장자만 알면 파일을 읽고 쓸 수 있다. 그러나 텍스트의 경우에는 약간 예외적인데
같은 txt파일이지만 인코딩방식에 따라 문자열을 다르게 읽기 때문이다.
위 결과 역시 byte문자열로 읽혀있는것을 볼 수 있다. 따라서 파이썬에서 읽을 수 있도록 문자형식을 변환해주어야 한다.

파이썬3는 기본적으로 유니코드를 지원한다.
유니코드 -> 아스키코드등 다른형식으로 변경하기 위해선 encode
기타형식 -> 유니코드로 변경하기 위해선 decode를 사용하면 된다. (혹은 str( string, encoding='utf-8') 등으로 사용가능)
위 코드를 약간 수정하여 type을 변환하면



from  urllib.request import urlopen

text = urlopen('http://doohaproject.tistory.com/attachment/cfile2.uf@25A2F43359777C510E95C5.txt')
string = text.read()
string2 = string.decode('unicode_escape')

print(type(string), string)
print(type(string2), string2)


<class 'bytes'> b'import csv\r\n\r\ncsvFile = open("./test.csv", \'w+\')\r\n\r\ntry:\r\n    writer = csv.writer(csvFile)\r\n    writer.writerow((\'number\', \'number plus 2 \', \'number times 2\'))\r\n    for i in range(10):\r\n        writer.writerow((i, i+2, i*2))\r\nfinally:\r\n    csvFile.close()'

<class 'str'> import csv


csvFile = open("./test.csv", 'w+')


try:

    writer = csv.writer(csvFile)

    writer.writerow(('number', 'number plus 2 ', 'number times 2'))

    for i in range(10):

        writer.writerow((i, i+2, i*2))

finally:

    csvFile.close()


제대로 나오는 것을 볼 수 있다.


HTML문서의 경우 <head>내부 태그에 명시되어 있으므로 이를 참조하여 인코딩 해주면 된다.

<meta charset="utf-8">



2. CSV 파일


이전에 포스팅 했던 것처럼 python 내부의 csv 라이브러리를 활용하면 크게 어려운 문제는 아니다.

그러나 csv라이브러리는 로컬에 파일이 있는 것을 가정하고 사용하는 것이기 때문에 실시간으로 내용을 확인해야하는경우 문제가 있다.

(파일을 직접 받고 파일 위치를 명시하여 참조하는 방법, 파일을 다운로드하는 스크립트를 작성후, 읽고 삭제하는 방법도 있음.)


역시 http://doohaproject.tistory.com/22 에 파일을 기준으로 

.



'프로젝트 > 파이썬' 카테고리의 다른 글

Python Date(날짜)  (3) 2017.08.08
웹 크롤링 - 데이터 저장  (0) 2017.07.26
웹 크롤링 - 데이터 저장(링크)  (0) 2017.07.25
pip 오류 - Failed building wheel for cryptography  (0) 2017.07.17
파이썬 웹 크롤링  (0) 2017.06.26