2013-09-23 12 views
16

Sto cercando di creare un tavolo raschiare con BeautifulSoup. Ho scritto questo codice Python:Python BeautifulSoup tabelle scrapbook

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'] 

Ho bisogno di grattare Nome, Cognome, Email.

risposta

21

Loop su righe della tabella (tr tag) e ottenere il testo delle celle (td tag) all'interno:

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) 

stampe:

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

proposito, [2:] fetta viene proposto di saltare due intestazione filari.

UPD, ecco come è possibile salvare i risultati in file 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

si può chiarire il motivo per cui è necessario il [2:] nella prima linea? – AZhao

+0

@AZhao sicuro, è lì nella risposta - per saltare le 2 righe di intestazione. – alecxe

Problemi correlati