Nice programing

BeautifulSoup의 태그에 속성이 있는지 테스트

nicepro 2020. 12. 10. 21:10
반응형

BeautifulSoup의 태그에 속성이 있는지 테스트


<script>문서의 모든 태그를 가져온 다음 특정 속성의 존재 (또는 부재)에 따라 각 태그를 처리하고 싶습니다 .

예를 들어, 각 <script>태그에 대해 속성 for이 있으면 무언가를 수행하십시오. 그렇지 않으면 속성 bar이 있으면 다른 작업을 수행하십시오.

현재 내가하고있는 일은 다음과 같습니다.

outputDoc = BeautifulSoup(''.join(output))
scriptTags = outputDoc.findAll('script', attrs = {'for' : True})

하지만 이런 식으로 모든 <script>태그를 for속성으로 필터링 하지만 다른 태그 ( 속성 이없는 태그)는 잃어 버렸습니다 for.


내가 잘 이해한다면 모든 스크립트 태그를 원하고 그 안에 몇 가지 속성을 확인 하시겠습니까?

scriptTags = outputDoc.findAll('script')
for script in scriptTags:
    if script.has_attr('some_attribute'):
        do_something()        

향후 참조를 위해 has_key는 더 이상 사용되지 않습니다. beautifulsoup 4입니다. 이제 has_attr을 사용해야합니다.

scriptTags = outputDoc.findAll('script')
  for script in scriptTags:
    if script.has_attr('some_attribute'):
      do_something()  

속성별로 필터링하는 데 람다가 필요하지 않습니다. 간단히 설정하면됩니다 src=True.

soup = bs4.BeautifulSoup(html)

# Find all with a specific attribute

tags = soup.find_all(src=True)
tags = soup.select("[src]")

# Find all meta with either name or http-equiv attribute.

soup.select("meta[name],meta[http-equiv]")

# find any tags with any name or source attribute.

soup.select("[name], [src]")

# find first/any script with a src attribute.

tag = soup.find('script', src=True)
tag = soup.select_one("script[src]")

# find all tags with a name attribute beginning with foo
# or any src beginning with /path
soup.select("[name^=foo], [src^=/path]")

# find all tags with a name attribute that contains foo
# or any src containing with whatever
soup.select("[name*=foo], [src*=whatever]")

# find all tags with a name attribute that endwith foo
# or any src that ends with  whatever
soup.select("[name$=foo], [src$=whatever]")

re를 find / find_all 등과 함께 사용할 수도 있습니다. :

import re
# starting with
soup.find_all("script", src=re.compile("^whatever"))
# contains
soup.find_all("script", src=re.compile("whatever"))
# ends with 
soup.find_all("script", src=re.compile("whatever$"))

속성이있는 태그 만 가져와야하는 경우 람다를 사용할 수 있습니다.

soup = bs4.BeautifulSoup(YOUR_CONTENT)
  • 속성이있는 태그
tags = soup.find_all(lambda tag: 'src' in tag.attrs)

또는

tags = soup.find_all(lambda tag: tag.has_attr('src'))
  • 속성이있는 특정 태그
tag = soup.find(lambda tag: tag.name == 'script' and 'src' in tag.attrs)
  • 기타 ...

유용 할 것이라고 생각했습니다.


일부 속성이 있는지 확인할 수 있습니다.

scriptTags = outputDoc.findAll ( 'script', some_attribute = True)
scriptTags의 스크립트 :
    do_something ()

pprint 모듈을 사용하여 요소의 내용을 검사 할 수 있습니다.

from pprint import pprint

pprint(vars(element))

bs4 요소에서 이것을 사용하면 다음과 비슷한 내용이 인쇄됩니다.

{'attrs': {u'class': [u'pie-productname', u'size-3', u'name', u'global-name']},
 'can_be_empty_element': False,
 'contents': [u'\n\t\t\t\tNESNA\n\t'],
 'hidden': False,
 'name': u'span',
 'namespace': None,
 'next_element': u'\n\t\t\t\tNESNA\n\t',
 'next_sibling': u'\n',
 'parent': <h1 class="pie-compoundheader" itemprop="name">\n<span class="pie-description">Bedside table</span>\n<span class="pie-productname size-3 name global-name">\n\t\t\t\tNESNA\n\t</span>\n</h1>,
 'parser_class': <class 'bs4.BeautifulSoup'>,
 'prefix': None,
 'previous_element': u'\n',
 'previous_sibling': u'\n'}

속성에 액세스하려면-클래스 목록을 예로 들어 보겠습니다. 다음을 사용하십시오.

class_list = element.attrs.get('class', [])

다음 접근 방식을 사용하여 요소를 필터링 할 수 있습니다.

for script in soup.find_all('script'):
    if script.attrs.get('for'):
        # ... Has 'for' attr
    elif "myClass" in script.attrs.get('class', []):
        # ... Has class "myClass"
    else: 
        # ... Do something else

참고 URL : https://stackoverflow.com/questions/5015483/test-if-an-attribute-is-present-in-a-tag-in-beautifulsoup

반응형