2012-10-25 2 views
8

BeautifulSoup을 사용하여 this data table의 첫 번째와 세 번째 열을 추출하려고합니다. HTML을 보면 첫 번째 열은 <th> 태그입니다. 관심있는 다른 열은 <td> 태그입니다. 어쨌든, 나가 나가기 수 있던 모두는 꼬리표를 가진 란의 명부이다. 그러나, 나는 그 텍스트를 원한다.BeautifulSoup을 사용하여 테이블에서 선택된 열 추출하기

table은 이미 목록이므로 findAll(text=True)을 사용할 수 없습니다. 다른 양식의 첫 번째 열의 목록을 가져 오는 방법을 모르겠습니다.

from BeautifulSoup import BeautifulSoup 
from sys import argv 
import re 

filename = argv[1] #get HTML file as a string 
html_doc = ''.join(open(filename,'r').readlines()) 
soup = BeautifulSoup(html_doc) 
table = soup.findAll('table')[0].tbody.th.findAll('th') #The relevant table is the first one 

print table 
+0

은 행 기반은 (비록 잘못 될 수있다). 행을 반복하고 해당 열을 추출하여 원하는 데이터 구조에 추가하여 근사치를 계산할 수 있다고 상상해보십시오. – RocketDonkey

+0

나는 그것을 시도하지만, 여전히 텍스트를 꺼낼 수 없었다. 나는 그 부분을 포함하도록 나의 대답을 업데이트 할 것이다. 아마 더 쉬운 방법 일 것입니다. – mac389

답변

22

당신은이 코드를 시도 할 수 있습니다 : 당신이 코드를 그냥 URL에 연결하고 HTML을 가져 볼 수 있듯이

import urllib2 
from BeautifulSoup import BeautifulSoup 

url = "http://www.samhsa.gov/data/NSDUH/2k10State/NSDUHsae2010/NSDUHsaeAppC2010.htm" 
soup = BeautifulSoup(urllib2.urlopen(url).read()) 

for row in soup.findAll('table')[0].tbody.findAll('tr'): 
    first_column = row.findAll('th')[0].contents 
    third_column = row.findAll('td')[2].contents 
    print first_column, third_column 

을하고, BeautifulSoup로는 첫 번째 테이블, 다음 모든 'TR'을 찾습니다 'th'인 첫 번째 열과 'td'인 세 번째 열을 선택합니다.

+0

정확히 내가했을 것입니다. 좋은 대답. – That1Guy

3

@ jonhkr의 답변 외에도 나는 내가 생각해 낸 대체 솔루션을 게시 할 것이라고 생각했습니다. 웹 페이지에 전화를 걸어 jonhkr의 대답과는 달리

#!/usr/bin/python 

from BeautifulSoup import BeautifulSoup 
from sys import argv 

filename = argv[1] 
#get HTML file as a string 
html_doc = ''.join(open(filename,'r').readlines()) 
soup = BeautifulSoup(html_doc) 
table = soup.findAll('table')[0].tbody 

data = map(lambda x: (x.findAll(text=True)[1],x.findAll(text=True)[5]),table.findAll('tr')) 
print data 

이 광산은 당신이 당신의 컴퓨터에 저장하고 명령 행 인수로 전달 있다고 가정합니다. 예를 들어이 코드를 시도 할 수 있습니다

python file.py table.html 
0

또한 난 당신이 HTML 표현으로 전체 열을 얻을 수 있습니다 생각하지 않는다

import requests 
from bs4 import BeautifulSoup 
page =requests.get("http://www.samhsa.gov/data/NSDUH/2k10State/NSDUHsae2010/NSDUHsaeAppC2010.htm") 
soup = BeautifulSoup(page.content, 'html.parser') 
for row in soup.findAll('table')[0].tbody.findAll('tr'): 
    first_column = row.findAll('th')[0].contents 
    third_column = row.findAll('td')[2].contents 
    print (first_column, third_column) 
관련 문제