2012-07-16 4 views
2

BeautifulSoup를 사용하여 태그 만 일치 시키려면 표시된 class 속성 및 기타 태그가 아닌 class 속성을으로 지정하면됩니까? 예를 들어,이 간단한 HTML에서 :BeautifulSoup를 사용하여 명시된 클래스 만 포함하고 다른 태그는 포함하지 않는 태그는 어떻게 일치합니까?

<html> 
<head> 
    <title> 
    Title here 
    </title> 
</head> 
<body> 
    <div class="one two"> 
    some content here 
    </div> 
    <div class="two"> 
    more content here 
    </div> 
</body> 
</html> 

class="two"div 만 일치하지만, class="one two"div 일치하지 않을 수 있습니까? 누락 된 정보가 없으면 that section 설명서가 나에게 어떤 아이디어도주지 않습니다. 내가 얻으려고

from bs4 import BeautifulSoup 

html = ''' 
<html> 
<head> 
    <title> 
    Title here 
    </title> 
</head> 
<body> 
    <div class="one two"> 
    should not be matched 
    </div> 
    <div class="two"> 
    this should be matched 
    </div> 
</body> 
</html> 
''' 

soup = BeautifulSoup(html) 
div_two = soup.find("div", "two") 
print(div_two.contents[0].strip()) 

this should be matched 대신 should not be matched을 인쇄 : 이것은 내가 현재 사용하고 코드입니다.

편집 :이 간단한 예제에서 클래스의 유일한 옵션은 "one two" 또는 "two"이지만 프로덕션 코드에서는 일치하려는 클래스가 클래스 "two"임을 알고 있습니다. 다른 태그는 알 수없는 "two" 외에 많은 수의 다른 클래스를 가질 수 있습니다.

관련 노트에 이전에 링크 된 버전 3이 아닌 documentation for version 4을 읽는 것도 도움이됩니다.

답변

4

시도 :

divs = soup.findAll('div', class="two") 

for div in divs: 
    if div['class'] == ['two']: 
     pass # handle class="two" 
    else: 
     pass # handle other cases, including but not limited to "one two" 
+0

유일한 문제는 태그에 어떤 클래스가 있는지 알 수없는 경우입니다. +1하지만 가능한 경우 내 편집을 참조하십시오. –

+0

당신의 대답은 기본적으로 내 것과 같기 때문에 편집에 도입 된 변경 사항을 통합하면 필답을 받아들이고 내 대답을 삭제합니다. –

+0

@RicardoAltamirano 예의 주셔서 감사합니다. 편집 됨. –

0

희망, 코드가 도움이 아래. 나는 이것을 시도하지는 않았지만.

soup.find("div", { "class" : "two" }) 
+0

문서에 따르면, 그것은'soup.find ("div", "two") '과 동일합니다. –