2013-10-21 4 views
0

을 정의되지 않습니다파이썬 CSV는 나는 다음과 같은 코드를 사용하고

from bs4 import BeautifulSoup 
import csv 
soup = BeautifulSoup (open("43rd-congress.htm")) 

final_link = soup.p.a 
final_link.decompose() 


f = csv.writer(open("43rd_congress_all.csv", "w")) 
f.writerow(["Name","Years","Position","Party", "State", "Congress", "Link"]) 
trs = soup.find_all('tr') 

for tr in trs: 
    for link in tr.find_all('a'): 
     fulllink = link.get ('href') 

     print fulllink #print in terminal to verify results 

     tds = tr.find_all("td") 

     try: #we are using "try" because the table is not well formatted. This allows the program to continue after encountering an error. 
      names = str(tds[0].get_text()) # This structure isolate the item by its column in the table and converts it into a string. 
      years = str(tds[1].get_text()) 
      positions = str(tds[2].get_text()) 
      parties = str(tds[3].get_text()) 
      states = str(tds[4].get_text()) 
      congress = tds[5].get_text() 

     except: 
      print "bad tr string" 
      continue #This tells the computer to move on to the next item after it encounters an error 

     print names, years, positions, parties, states, congress 
     f.writerow([names, years, posiitons, parties, states, congress, fullLink]) 

그리고 나는 다음과 같은 오류가 발생합니다. 온라인 34 (마지막 줄)입니다. IndentationError : 예기치 않은 들여 쓰기. 여기에서이 자습서를 사용하고 있습니다. http://jeriwieringa.com/blog/2012/11/04/beautiful-soup-tutorial-part-1/

들여 쓰기에 문제가 있다고 생각됩니다. 다음 코드를 사용하면 9 행에서 csv가 정의되지 않은 오류가 발생합니다.

+1

이전에 간단한 Python 프로그램을 사용해 보았습니까? 들여 쓰기는 일종의 대단한 일입니다 (파이썬 포함) –

+0

두 가지를 통해 작업했습니다. 하나는 codeacademy에 의해, 다른 하나는 LPTHW에 의해. –

+0

'위치'의 철자가 잘못 되었기 때문에 마지막 줄에 오류가 발생할 수 있습니다. – ishikun

답변

4

오류는 매우 분명합니다.

print names, years, positions, parties, states, congress 
     f.writerow([names, years, posiitons, parties, states, congress, fullLink]) 

print names, years, positions, parties, states, congress 
    f.writerow([names, years, posiitons, parties, states, congress, fullLink]) 

파이썬 코드의 예기치 않은 들여 쓰기를 싫어해야하고, f.writerowprint 문으로 들여 쓰기의 동일한 수준을 가져야한다.

indentation here에 대한 자세한 내용을 읽으십시오. 파이썬에서 가장 기본적이고 중요한 개념 중 하나이기 때문에이 것을 완전히 이해할 때까지는 더 이상 진행하지 말 것을 권한다.

는 파일의 시작 부분에

import csv 

에 당신이 필요로하는 CSV 문제,

를 해결하려면.

+0

나는 그 수정을 시도한 다음 9 행의 오류로 간다. csv가 정의되지 않은 상태. –

+0

@Rob 인 경우 CSV는 –

+2

@ RoB를 가져와야하는 모듈입니다. 당신을 화나게하지는 않겠지 만, XML을 파싱하기 전에 파이썬 튜토리얼 (좀 더 기본적인 튜토리얼)을 사용하십시오. – karthikr

관련 문제