웹에서 가져온 html 테이블을 파이썬에서 csv 파일로 만드는 방법
조회수 1573회
https://en.wikipedia.org/wiki/Comparison_of_text_editors에 있는 첫 번째 테이블(list of text editors)을 가져와서 csv 파일로 만드는 연습을 하고 있습니다.
아래와 같이 파이썬 코드를 만들었고,
import csv
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("https://en.wikipedia.org/wiki/Comparison_of_text_editors")
bs0bj = BeautifulSoup(html, "html.parser")
table = bs0bj.findAll("table", {"class":"wikitable"})[0]
rows = table.findAll("tr")
csvFile = open("../files/editors.csv", 'wt')
writer = csv.writer(csvFile)
try:
for row in rows:
csvRow = [ ]
for cell in row.findAll(['td', 'th']):
csvRow.append(cell.get_text())
writer.writerow(csvRow)
finally:
csvFile.close()
이렇게 에러가 났습니다.
FileNotFoundError Traceback (most recent call last) in () 10 table = bs0bj.findAll("table", {"class":"wikitable"})[0] 11 rows = table.findAll("tr") ---> 12 csvFile = open("../files/editors.csv", 'wt') 13 writer = csv.writer(csvFile) 14
FileNotFoundError: [Errno 2] No such file or directory: '../files/editors.csv'
파이썬에서 csv 파일을 만들 수 있는 것으로 아는데, 어디에 문제가 있는 것인지 도움 부탁 드립니다.
-
(•́ ✖ •̀)
알 수 없는 사용자 - 〉
1 답변
-
일단 에러메시지는 파일을 찾을 수 없다는 겁니다.
../files/editors.csv 라고 했는데 일단 ../files 디렉토리가 있는지 살펴보시기 바랍니다.
그리고 테스트를 해보니 윈도우에서 위의 예제는 인코딩 에러가 있을 수 있습니다.
Enrico Tröger
라는 문자열이 존재하는데 윈도우 인코딩 cp949 에서 움라우트(점 두개 있는 독일문자)는 표현할 수 없는 문자입니다.
아래의 예제로 테스트 해보시기 바랍니다. 반복문이나 리소스 처리를 간결하게 수정했습니다.
with 문울 이용하면 자동으로 파일 리소스를 정리해줍니다.
_csv.writer 에는 writerows 라는 여러라인을 동시에 저잘 할 수 있는 메소드가 있습니다.
import csv from urllib.request import urlopen from bs4 import BeautifulSoup import codecs html = urlopen("https://en.wikipedia.org/wiki/Comparison_of_text_editors") bs0bj = BeautifulSoup(html, "html.parser") table = bs0bj.findAll("table", {"class":"wikitable"})[0] rows = table.findAll("tr") with codecs.open("editors.csv", 'w', 'utf-8') as csvFile: writer = csv.writer(csvFile) csvRows = map(lambda row:(cell.get_text() for cell in row.findAll(['td', 'th'])), rows) writer.writerows(csvRows)
댓글 입력