1
Wikipedia 기사에서 테이블의 데이터를 자동으로 스크래핑하는 데 약간의 문제가 있습니다. 먼저 인코딩 오류가 발생했습니다. UTF-8을 지정했는데 오류가 사라졌지만 스크랩 한 데이터에 많은 문자가 올바르게 표시되지 않습니다. 당신은 내가 완전한 초보자 오전 코드에서 말할 수있을 것입니다 : pswaminathan으로Python + BeautifulSoup CSV로 내보내기
from bs4 import BeautifulSoup
import urllib2
wiki = "http://en.wikipedia.org/wiki/Anderson_Silva"
header = {'User-Agent': 'Mozilla/5.0'} #Needed to prevent 403 error on Wikipedia
req = urllib2.Request(wiki,headers=header)
page = urllib2.urlopen(req)
soup = BeautifulSoup(page)
Result = ""
Record = ""
Opponent = ""
Method = ""
Event = ""
Date = ""
Round = ""
Time = ""
Location = ""
Notes = ""
table = soup.find("table", { "class" : "wikitable sortable" })
f = open('output.csv', 'w')
for row in table.findAll("tr"):
cells = row.findAll("td")
#For each "tr", assign each "td" to a variable.
if len(cells) == 10:
Result = cells[0].find(text=True)
Record = cells[1].find(text=True)
Opponent = cells[2].find(text=True)
Method = cells[3].find(text=True)
Event = cells[4].find(text=True)
Date = cells[5].find(text=True)
Round = cells[6].find(text=True)
Time = cells[7].find(text=True)
Location = cells[8].find(text=True)
Notes = cells[9].find(text=True)
write_to_file = Result + "," + Record + "," + Opponent + "," + Method + "," + Event + "," + Date + "," + Round + "," + Time + "," + Location + "\n"
write_to_unicode = write_to_file.encode('utf-8')
print write_to_unicode
f.write(write_to_unicode)
f.close()
CSV 모듈 (http://docs.python.org/2/library/csv.html)을 사용해 보셨습니까? 그것은 인용 부호 등을 처리합니다.이 문서는 또한 다른 인코딩의 텍스트를 작성하는 올바른 방향을 제시합니다. 귀하의 특정 문제에 대한,하지만 ... UTF - 8로 올바르게 표시되지 않는 이유는 무엇입니까? 해당 페이지의 메타 태그에 따르면 charset은 UTF-8입니다. – pswaminathan