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
>>>
그건 속임수 였어! 코드가 작동하고 필요에 따라 수정할 수 있어야합니다. 많은 감사합니다. 마지막 질문 하나. th와 tr에 대한 표를 검색 할 때를 제외하고 코드를 따라갈 수 있습니다. 단순히 테이블을 검색하고 테이블 헤더와 테이블 행을 반환하는 것입니까? 테이블 행만 원하면 tr 만 검색하면됩니까? 다시 한 번 감사드립니다. – Btibert3
예.'.findChildren ([ 'th', 'tr'])'은 태그 유형이 'th' 또는'tr' 인 요소를 검색합니다. 단지'tr' 요소를 찾고 싶다면'.findChildren ('tr')'(목록이 아니라 문자열 만) –
[PyQuery] (https://pythonhosted.org) /pyquery/api.html)은 BeautifulSoup에 대한 정말 멋진 대안입니다. –