2012-01-04 16 views
14

का उपयोग करके एनएच तत्व प्राप्त करना एक बड़ी तालिका से मैं पंक्तियों 5, 10, 15, 20 ... सुंदर सूप का उपयोग करना चाहता हूं। मैं यह कैसे करु? क्या NextSibling और एक बढ़ती काउंटर जाने का रास्ता है?सुंदर सूप

उत्तर

31

तुम भी findAll इस्तेमाल कर सकते हैं एक सूची में सभी पंक्तियों को पाने के लिए और उसके बाद सिर्फ टुकड़ा सिंटैक्स का उपयोग तत्वों कि आप की आवश्यकता का उपयोग करने की:

rows = soup.findAll('tr')[4::5] 
+0

यह साफ़ है। ध्यान दें कि सभी विधि एक सरणी लौटाती है, इसलिए यह बहुत अच्छा है। – JasTonAChair

1

एक सामान्य समाधान के रूप में, आप तालिका में बदल सकते हैं चल रहा है एक नेस्टेड सूची और दोहराएं ...

import BeautifulSoup 

def listify(table): 
    """Convert an html table to a nested list""" 
    result = [] 
    rows = table.findAll('tr') 
    for row in rows: 
    result.append([]) 
    cols = row.findAll('td') 
    for col in cols: 
     strings = [_string.encode('utf8') for _string in col.findAll(text=True)] 
     text = ''.join(strings) 
     result[-1].append(text) 
    return result 

if __name__=="__main__": 
    """Build a small table with one column and ten rows, then parse into a list""" 
    htstring = """<table> <tr> <td>foo1</td> </tr> <tr> <td>foo2</td> </tr> <tr> <td>foo3</td> </tr> <tr> <td>foo4</td> </tr> <tr> <td>foo5</td> </tr> <tr> <td>foo6</td> </tr> <tr> <td>foo7</td> </tr> <tr> <td>foo8</td> </tr> <tr> <td>foo9</td> </tr> <tr> <td>foo10</td> </tr></table>""" 
    soup = BeautifulSoup.BeautifulSoup(htstring) 
    for idx, ii in enumerate(listify(soup)): 
     if ((idx+1)%5>0): 
      continue 
     print ii 

है कि ...

[[email protected] ~]$ python testme.py 
['foo5'] 
['foo10'] 
[[email protected] ~]$ 
1

एक अन्य विकल्प है, अगर आप कच्चे एचटीएमएल पसंद करते हैं ...

"""Build a small table with one column and ten rows, then parse it into a list""" 
htstring = """<table> <tr> <td>foo1</td> </tr> <tr> <td>foo2</td> </tr> <tr> <td>foo3</td> </tr> <tr> <td>foo4</td> </tr> <tr> <td>foo5</td> </tr> <tr> <td>foo6</td> </tr> <tr> <td>foo7</td> </tr> <tr> <td>foo8</td> </tr> <tr> <td>foo9</td> </tr> <tr> <td>foo10</td> </tr></table>""" 
result = [html_tr for idx, html_tr in enumerate(soup.findAll('tr')) \ 
    if (idx+1)%5==0] 
print result 

चल रहा है कि ...

[[email protected] ~]$ python testme.py 
[<tr> <td>foo5</td> </tr>, <tr> <td>foo10</td> </tr>] 
[[email protected] ~]$ 
1

यह आसानी से सुंदर सूप में select साथ किया जा सकता है अगर आप पंक्ति संख्या पता चयन किया जाना । (नोट: यह बीएस 4 में है)

row = 5 
while true 
    element = soup.select('tr:nth-of-type('+ row +')') 
    if len(element) > 0: 
     # element is your desired row element, do what you want with it 
     row += 5 
    else: 
     break 
संबंधित मुद्दे