2014-02-10 4 views
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() 
+2

CSV 모듈 (http://docs.python.org/2/library/csv.html)을 사용해 보셨습니까? 그것은 인용 부호 등을 처리합니다.이 문서는 또한 다른 인코딩의 텍스트를 작성하는 올바른 방향을 제시합니다. 귀하의 특정 문제에 대한,하지만 ... UTF - 8로 올바르게 표시되지 않는 이유는 무엇입니까? 해당 페이지의 메타 태그에 따르면 charset은 UTF-8입니다. – pswaminathan

답변

1

크게 도움이 될 것입니다 csv 모듈을 사용하여 지적했다. 여기에 내가 그것을 할 방법은 다음과 같습니다

table = soup.find('table', {'class': 'wikitable sortable'}) 
with open('out2.csv', 'w') as f: 
    csvwriter = csv.writer(f) 
    for row in table.findAll('tr'): 
     cells = [c.text.encode('utf-8') for c in row.findAll('td')] 
     if len(cells) == 10: 
      csvwriter.writerow(cells) 

토론

  • 을 CSV 모듈을 사용하여, 나는 내 출력 파일에 연결된 csvwriter 객체를 만들었습니다.
  • with 명령을 사용하면 완료 후 출력 파일을 닫을 염려가 없습니다. with 블록 다음에 닫힙니다.
  • 내 코드에서 cellstr 태그 내의 td 태그에서 추출한 UTF8 인코딩 텍스트 목록입니다.
  • 보다 간결한 구조 인 c.text을 사용했습니다.