BeautifulSoup ile ayrıştırılacak bir HTML dosyanız varsa, bu oldukça basit olmalıdır. Genel fikir, findChildren
yöntemini kullanarak tablonuza gitmek, daha sonra string
özelliği ile hücrenin içindeki metin değerini alabilirsiniz.
>>> from BeautifulSoup import BeautifulSoup
>>>
>>> html = """
... <html>
... <body>
... <table>
... <th><td>column 1</td><td>column 2</td></th>
... <tr><td>value 1</td><td>value 2</td></tr>
... </table>
... </body>
... </html>
... """
>>>
>>> soup = BeautifulSoup(html)
>>> tables = soup.findChildren('table')
>>>
>>> # This will get the first (and only) table. Your page may have more.
>>> my_table = tables[0]
>>>
>>> # You can find children with multiple tags by passing a list of strings
>>> rows = my_table.findChildren(['th', 'tr'])
>>>
>>> for row in rows:
... cells = row.findChildren('td')
... for cell in cells:
... value = cell.string
... print "The value in this cell is %s" % value
...
The value in this cell is column 1
The value in this cell is column 2
The value in this cell is value 1
The value in this cell is value 2
>>>
Bu hile oldu! Kod çalıştı ve gerektiğinde değiştirebilmeliydim. Çok teşekkürler. Son bir soru. Çocuklar için tabloyu aradığınızda yukarıdaki kodu takip edebilirim. Bu sadece masamı mı arıyor ve hem tablo başlığını hem de tablo satırlarını döndürüyor mu? Sadece tablo satırlarını istediysem, sadece sadece tr'i arayabilirim? tekrar çok teşekkürler! – Btibert3
Evet, '.findChildren (['th', 'tr'])' 'th' veya' tr' etiket türüne sahip öğeleri arıyor. Eğer sadece 'tr 'elemanlarını bulmak istiyorsanız' .findChildren (' tr ') '(bir liste değil, sadece dize) not –
[PyQuery] (https://pythonhosted.org /pyquery/api.html), BeautifulSoup'a gerçekten çok güzel bir alternatif. –