일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- 파이썬 장고
- 확률공부
- 머신러닝
- 파이썬 가상환경
- ultrawave sensor
- 파이참 가상환경
- 베이즈법칙
- 초음파
- 웹 크롤링
- 초대장
- 확률모델
- MEGA2560
- urlretrieve
- 텍스트 검색
- 파이썬
- 파이썬 웹 개발
- 베이즈이론
- 티스토리
- ssh전송
- ssh원격
- bs4
- CSV
- 아두이노
- 아두이노 스케치
- 스케치
- ssh파일
- Python
- non block
- Arduino
- BeautifulSoup
- Today
- Total
잡
웹 크롤링 - 문서 읽기 본문
웹 크롤러를 제작하면서 단순히 HTML코드뿐 아니라 pdf, txt, csv등 여러 파일을 읽어야 하는 순간이 생기게 된다.
1. 텍스트 파일
사실 텍스트 파일을 직접 올리는 경우는 많지 않다. 그러나 문서만을 다루는 사이트들의 경우 텍스트 파일을 다루는 경우도 종종 있다.
http://doohaproject.tistory.com/22 에 있는 예제 파일을 기준으로 파일을 읽는다면
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()'
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 |