2010-01-06 3 views
14

나는 웹에서 데이터를 긁어 내고 HTML 테이블을 읽는 Python과 BeautifulSoup을 배우고있다. 나는 이것을 Open Office로 읽을 수 있으며 Table # 11이라고 말합니다.BeautifulSoup를 사용하여 특정 테이블의 모든 행을 어떻게 얻습니까?

BeautifulSoup이 선호되는 선택 인 것 같습니다. 그러나 누군가 특정 테이블과 모든 행을 가져 오는 방법을 말해 줄 수 있습니까? 모듈 문서를 살펴 봤지만 주위에 머리를 쓸 수는 없습니다. 내가 찾은 많은 사례는 필자가 필요로하는 것보다 더 많은 것으로 보인다.

답변

24

BeautifulSoup과 (과) 구문 분석 할 HTML 묶음이있는 경우에는 매우 간단합니다. 일반적인 아이디어는 findChildren 메소드를 사용하여 테이블로 이동 한 다음 string 속성을 사용하여 셀 내부에서 텍스트 값을 가져올 수 있습니다.

>>> 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 
>>> 
+0

그건 속임수 였어! 코드가 작동하고 필요에 따라 수정할 수 있어야합니다. 많은 감사합니다. 마지막 질문 하나. th와 tr에 대한 표를 검색 할 때를 제외하고 코드를 따라갈 수 있습니다. 단순히 테이블을 검색하고 테이블 헤더와 테이블 행을 반환하는 것입니까? 테이블 행만 원하면 tr 만 검색하면됩니까? 다시 한 번 감사드립니다. – Btibert3

+2

예.'.findChildren ([ 'th', 'tr'])'은 태그 유형이 'th' 또는'tr' 인 요소를 검색합니다. 단지'tr' 요소를 찾고 싶다면'.findChildren ('tr')'(목록이 아니라 문자열 만) –

+0

[PyQuery] (https://pythonhosted.org) /pyquery/api.html)은 BeautifulSoup에 대한 정말 멋진 대안입니다. –

관련 문제