2013-09-05 2 views
0

HTML 테이블을 2 차원 파이썬 목록 (목록 목록)으로 변환하려고합니다. 세 개의 "열"은 해당 HTML 표 셀의 텍스트이며 잘 작동합니다. 그러나 하나의 "열"은 해당 HTML 셀의 링크 ID 여야하며 해당 속성에 액세스 할 수 없습니다.BeautifulSoup에서 어린이 특성에 액세스 할 수 없습니다.

링크의 ID를 얻으려고 할 때 문제가 발생합니다. 해당 요소의 .content를 인쇄하면 "Action"이라고 표시됩니다. 해당 요소의 [ 'id'] 색인에 액세스하려고하면 오류가 발생합니다. 뭐가 잘못 되었 니?

bs = BeautifulSoup(page) 

    table = bs.find("table", id="ctl00_ContentPlaceHolder1_Name_Reports1_TabContainer1_TabPanel1_dgReports") 

    def notHeader(css_class): 
     return css_class is not "gridviewheader" 

    rows = table.find_all("tr", class_=notHeader) 

    result = [] 

    for x in range(0, len(rows)): 
     allcols = rows[x].findAll('td') 

     tempRow = [] 
     print(allcols[0].contents[0]) #only prints Action 
     tempRow.append(allcols[0].contents[0]['id']) #TypeError: string indices must be integers 
     tempRow.append(allcols[2].string) 
     tempRow.append(allcols[3].string) 
     tempRow.append(allcols[5].string) 
     amended = -1 
     for existing in result: 
      if tempRow[1] == existing[1] and tempRow[2] == existing[2]: 
       amended = 1 
     if amended == -1: 
      result.append(tempRow) 

    print (ids) 
+0

'Action' 만 출력하면'내용 [0]'은'NavigableString' 객체입니다; 웹 페이지 텍스트. –

+0

아마도'id' 속성은'' 태그에 있습니까? 이 경우'allcols [0] .attrs [ 'id']'또는'allcols [0] [ 'id']'를 사용하십시오. –

+0

@MartijnPieters : 어떻게 든 오류가 주어진 문자열이 된 것은 당연합니다. 그러나 BoeautifulScope 객체에서 문자열로 바뀐 위치를 파악할 수는 없습니까? – Jeff

답변

0

알아 낸 점 : find_all() 함수를 사용하여 헤더 행을 제거해야했습니다. find_all 라인을

rows = table.find_all("tr")[1:] 

으로 바 꾸었습니다. 헤더가 항상 첫 줄이므로 작동하기 때문입니다.

관련 문제