2016-03-18 31 views
5

Ciao, quindi applico find_all su beautifulsoup object e trova qualcosa, che è un bs4.element.ResultSet object o list.beautifulsoup: find_all su bs4.element.ResultSet oggetto o elenco?

Desidero eseguire ulteriormente find_all, ma non è consentito su bs4.element.ResultSet object. Posso scorrere ogni elemento dello bs4.element.ResultSet object per fare find_all. Ma posso evitare il looping e convertirlo nuovamente in un beautifulsoup object?

Vedere il codice per i dettagli per favore. Grazie

html_1 = """ 
<table> 
    <thead> 
     <tr class="myClass"> 
      <th>A</th> 
      <th>B</th> 
      <th>C</th> 
      <th>D</th> 
     </tr> 
    </thead> 
</table> 
""" 
soup = BeautifulSoup(html_1, 'html.parser') 

type(soup) #bs4.BeautifulSoup 

# do find_all on beautifulsoup object 
th_all = soup.find_all('th') 

# the result is of type bs4.element.ResultSet or similarly list 
type(th_all) #bs4.element.ResultSet 
type(th_all[0:1]) #list 

# now I want to further do find_all 
th_all.find_all(text='A') #not work 

# can I avoid this need of loop? 
for th in th_all: 
    th.find_all(text='A') #works 

risposta

8

ResultSet classe è una sottoclasse di un elenco e non un Tag class che ha le find* metodi definiti. Scorrendo i risultati del find_all() è l'approccio più comune:

th_all = soup.find_all('th') 
result = [] 
for th in th_all: 
    result.extend(th.find_all(text='A')) 

Di solito, CSS selectors può aiutare a risolvere in un colpo solo, tranne che non tutto si può fare con find_all() è possibile con il metodo select(). Ad esempio, non è disponibile la ricerca "testuale" nei selettori CSS bs4. Ma, se, ad esempio, si doveva trovare tutto, diciamo, b elementi all'interno th elementi, si potrebbe fare:

soup.select("th td") 
+0

Dopo aver copiato il risultato della soup.find_all a th_all, sarà di apportare modifiche al th_all riflettere in la minestra? –

+0

Sì, lo farà. Dipende dalla funzione che usi. Riferimento: https://beautiful-soup-4.readthedocs.io/en/latest/#modifying-the-tree –