2013-09-23 4 views
16

BeautifulSoup로 테이블 긁힌 자국을 만들려고합니다. 나는 놈, Cognome, 이메일을 긁어 필요Python BeautifulSoup 긁힌 테이블

import urllib2 
from bs4 import BeautifulSoup 

url = "http://dofollow.netsons.org/table1.htm" # change to whatever your url is 

page = urllib2.urlopen(url).read() 
soup = BeautifulSoup(page) 

for i in soup.find_all('form'): 
    print i.attrs['class'] 

:이 파이썬 코드를 썼다.

답변

21

테이블 행을 통해 루프 (tr 태그)와 내부 세포의 텍스트 (td 태그) 수 :

for tr in soup.find_all('tr')[2:]: 
    tds = tr.find_all('td') 
    print "Nome: %s, Cognome: %s, Email: %s" % \ 
      (tds[0].text, tds[1].text, tds[2].text) 

인쇄 :

Nome:  Massimo, Cognome:  Allegri, Email:  [email protected] 
Nome:  Alessandra, Cognome:  Anastasia, Email:  [email protected] 
... 

참고로, 여기 [2:] 슬라이스 두 개의 헤더를 건너입니다 행.

UPD, 여기 당신이 txt 파일에 결과를 저장하는 방법은 다음과 같습니다

with open('output.txt', 'w') as f: 
    for tr in soup.find_all('tr')[2:]: 
     tds = tr.find_all('td') 
     f.write("Nome: %s, Cognome: %s, Email: %s\n" % \ 
       (tds[0].text, tds[1].text, tds[2].text)) 
+0

당신은 명확하게 할 수 있습니다 당신이 필요로하는 이유 [2] 첫 번째 줄에? – AZhao

+0

@AZhao 확실한 것은 응답에 2 개의 헤더 행을 건너 뛰는 것입니다. – alecxe

관련 문제