[python] 클래스별로 요소를 찾는 방법

Beautifulsoup을 사용하여 “클래스”속성이있는 HTML 요소를 구문 분석하는 데 문제가 있습니다. 코드는 다음과 같습니다

soup = BeautifulSoup(sdata)
mydivs = soup.findAll('div')
for div in mydivs: 
    if (div["class"] == "stylelistrow"):
        print div

스크립트가 끝나고 “후”같은 줄에 오류가 발생합니다.

File "./beautifulcoding.py", line 130, in getlanguage
  if (div["class"] == "stylelistrow"):
File "/usr/local/lib/python2.6/dist-packages/BeautifulSoup.py", line 599, in __getitem__
   return self._getAttrMap()[key]
KeyError: 'class'

이 오류를 어떻게 제거합니까?



답변

BS3를 사용하여 주어진 클래스의 div 만 찾도록 검색을 구체화 할 수 있습니다.

mydivs = soup.findAll("div", {"class": "stylelistrow"})


답변

설명서에서 :

Beautiful Soup 4.1.2부터 키워드 인수를 사용하여 CSS 클래스로 검색 할 수 있습니다 class_ .

soup.find_all("a", class_="sister")

이 경우 다음 중 하나입니다.

soup.find_all("div", class_="stylelistrow")

또한 다음과 같이 작동합니다.

soup.find_all("div", class_="stylelistrowone stylelistrowtwo")


답변

업데이트 : 2016 beautifulsoup 최신 버전에서 ‘findAll’메소드의 이름이 ‘find_all’로 변경되었습니다. 공식 문서로 연결

분석법 이름 목록이 변경됨

따라서 대답은

soup.find_all("html_element", class_="your_class_name")


답변

BeautifulSoup 3에만 해당 :

soup.findAll('div',
             {'class': lambda x: x
                       and 'stylelistrow' in x.split()
             }
            )

이 모든 것을 찾을 수 있습니다 :

<div class="stylelistrow">
<div class="stylelistrow button">
<div class="button stylelistrow">


답변

간단한 방법은 다음과 같습니다.

soup = BeautifulSoup(sdata)
for each_div in soup.findAll('div',{'class':'stylelist'}):
    print each_div

findAll 이 아닌 findAll 의 케이스를 가져와야합니다.


답변

클래스별로 요소를 찾는 방법

Beautifulsoup을 사용하여 “class”속성을 사용하여 html 요소를 구문 분석하는 데 문제가 있습니다.

하나의 클래스로 쉽게 찾을 수 있지만 두 클래스의 교차로 찾으려면 조금 더 어렵습니다.

로부터 문서 (강조는 추가) :

둘 이상의 CSS 클래스 와 일치 하는 태그를 검색 하려면 CSS 선택기를 사용해야합니다.

css_soup.select("p.strikeout.body")
# [<p class="body strikeout"></p>]

명확하게하기 위해, 이는 취소 선과 본문 클래스 인 p 태그 만 선택합니다.

의 교차점에 대한 찾으려면 어떤 클래스의 집합 (안 교차로,하지만 노조)에서 것은, 당신은에 대한 목록을 제공 할 수 있습니다 class_(4.1.2)을 키워드 인수 :

soup = BeautifulSoup(sdata)
class_list = ["stylelistrow"] # can add any other classes to this list.
# will find any divs with any names in class_list:
mydivs = soup.find_all('div', class_=class_list) 

또한 findAll의 이름이 camelCase에서 더 Pythonic로 바뀌 었습니다 find_all.


답변

CSS 선택기

싱글 클래스 첫 경기

soup.select_one('.stylelistrow')

경기 목록

soup.select('.stylelistrow')

복합 클래스 (즉, AND 다른 클래스)

soup.select_one('.stylelistrow.otherclassname')
soup.select('.stylelistrow.otherclassname')

복합 클래스 이름의 공백은 class = stylelistrow otherclassname“.”으로 대체됩니다. 수업을 계속 추가 할 수 있습니다.

클래스 목록 (또는-존재하는 항목과 일치)

soup.select_one('.stylelistrow, .otherclassname')
soup.select('.stylelistrow, .otherclassname')

bs4 4.7.1 +

innerText문자열을 포함하는 특정 클래스

soup.select_one('.stylelistrow:contains("some string")')
soup.select('.stylelistrow:contains("some string")')

특정 하위 요소가있는 특정 클래스 (예 : a태그)

soup.select_one('.stylelistrow:has(a)')
soup.select('.stylelistrow:has(a)')