>  기사  >  백엔드 개발  >  Python이 Beautiful Soup 모듈을 사용하여 콘텐츠를 검색하는 방법에 대한 자세한 설명

Python이 Beautiful Soup 모듈을 사용하여 콘텐츠를 검색하는 방법에 대한 자세한 설명

高洛峰
高洛峰원래의
2017-03-31 09:47:212789검색

이 글에서는 Python에서 Beautiful Soup 모듈의 검색 방법 기능을 주로 소개합니다. 방법 다양한 유형의 필터링 매개변수에 따라 다양한 필터링을 수행하여 원하는 결과를 얻을 수 있습니다. 기사의 소개는 매우 자세하며 모든 사람이 참조할 수 있는 내용이 있습니다. 필요한 친구는 아래에서 살펴볼 수 있습니다.

서문

Beautiful Soup 모듈의 검색 기능을 사용하여 태그 이름, 태그 속성, 문서 텍스트 및 일반 기준으로 검색하겠습니다. 표현 .

검색 방법

뷰티플수프에 내장된 검색 방법은 다음과 같습니다.

  • 찾기 ()

  • find_all()

  • find_parent()

  • find_parents()

  • find_next_sibling()

  • find_next_siblings()

  • find_previous_sibling()

  • find_previous_siblings()

  • find_previous()

  • find_all_previous()

  • find_next ()

  • find_all_next()

find() 메소드를 사용하여 을 검색하세요.

먼저 테스트용 HTML 파일을 만들어야 합니다.


<html>
<body>
<p class="ecopyramid">
 <ul id="producers">
 <li class="producerlist">
  <p class="name">plants</p>
  <p class="number">100000</p>
 </li>
 <li class="producerlist">
  <p class="name">algae</p>
  <p class="number">100000</p>
 </li>
 </ul>
 <ul id="primaryconsumers">
 <li class="primaryconsumerlist">
  <p class="name">deer</p>
  <p class="number">1000</p>
 </li>
 <li class="primaryconsumerlist">
  <p class="name">rabbit</p>
  <p class="number">2000</p>
 </li>
 </ul>
 <ul id="secondaryconsumers">
 <li class="secondaryconsumerlist">
  <p class="name">fox</p>
  <p class="number">100</p>
 </li>
 <li class="secondaryconsumerlist">
  <p class="name">bear</p>
  <p class="number">100</p>
 </li>
 </ul>
 <ul id="tertiaryconsumers">
 <li class="tertiaryconsumerlist">
  <p class="name">lion</p>
  <p class="number">80</p>
 </li>
 <li class="tertiaryconsumerlist">
  <p class="name">tiger</p>
  <p class="number">50</p>
 </li>
 </ul>
</p>
</body>
</html>

find() 메소드를 통해 ff6d136ddc5fdfeffaf53ff6ee95f185 태그를 얻을 수 있으며, 기본적으로 가장 먼저 나타나는 태그를 얻습니다. 그런 다음 25edfb22a4f469ecb59f1190150159c6 태그를 가져오면 기본적으로 첫 번째 태그가 표시됩니다. 그런 다음 e388a4556c0f65e1904146cc1a846bee 태그를 가져오고 콘텐츠를 출력하여 첫 번째 태그를 가져왔는지 확인합니다.


from bs4 import BeautifulSoup
with open(&#39;search.html&#39;,&#39;r&#39;) as filename:
 soup = BeautifulSoup(filename,&#39;lxml&#39;)
first_ul_entries = soup.find(&#39;ul&#39;)
print first_ul_entries.li.p.string

find() 메소드는 다음과 같습니다.


find(name,attrs,recursive,text,**kwargs)

위 코드에서 볼 수 있듯이 find() 메소드는 name, attrs, recursive, text 및 **kwargs의 5개 매개변수를 허용합니다. 이름, 속성 및 텍스트 매개변수는 모두 find() 메서드에서 필터 역할을 하여 일치 결과의 정확성을 향상시킬 수 있습니다.

태그 검색

위 코드에서 ff6d136ddc5fdfeffaf53ff6ee95f185 태그를 검색하는 것 외에도 25edfb22a4f469ecb59f1190150159c6 반환된 결과는 일치하는 첫 번째 결과이기도 합니다.


tag_li = soup.find(&#39;li&#39;)
# tag_li = soup.find(name = "li")
print type(tag_li)
print tag_li.p.string

텍스트 검색

텍스트 콘텐츠만을 기반으로 검색하려면 text 매개변수만 전달할 수 있습니다.


search_for_text = soup.find(text=&#39;plants&#39;)
print type(search_for_text)
<class &#39;bs4.element.NavigableString&#39;>

반환된 결과도 NavigableString 개체입니다.

다음 HTML 텍스트 콘텐츠에 대해 정규식을 기준으로

검색


<p>The below HTML has the information that has email ids.</p>
 abc@example.com 
<p>xyz@example.com</p> 
 <span>foo@example.com</span>

abc@를 볼 수 있습니다. 예제 이메일 주소는 어떤 태그에도 포함되어 있지 않으므로 태그를 기반으로 이메일 주소를 찾을 수 없습니다. 이때 정규식을 사용하여 일치시킬 수 있습니다.


email_id_example = """
 <p>The below HTML has the information that has email ids.</p>
 abc@example.com
 <p>xyz@example.com</p>
 <span>foo@example.com</span>
 """
email_soup = BeautifulSoup(email_id_example,&#39;lxml&#39;)
print email_soup
# pattern = "\w+@\w+\.\w+"
emailid_regexp = re.compile("\w+@\w+\.\w+")
first_email_id = email_soup.find(text=emailid_regexp)
print first_email_id

일치에 정규식을 사용할 때 일치하는 항목이 여러 개인 경우 첫 번째 항목이 먼저 반환됩니다.

태그 속성 값으로 검색

태그 속성 값으로 검색할 수 있습니다.


search_for_attribute = soup.find(id=&#39;primaryconsumers&#39;)
print search_for_attribute.li.p.string

태그 기준 ID, 스타일, 제목 등 대부분의 속성에 대해 속성 값으로 검색이 가능합니다.

그러나 다음 두 가지 상황에서는 차이가 있습니다.

  • 사용자 정의 속성

  • 클래스( class ) 속성

더 이상 속성 값을 사용하여 직접 검색할 수 없지만 find() 함수에 전달하려면 attrs 매개변수를 사용해야 합니다.

맞춤 속성 기반 검색

HTML5에서는 태그에 속성을 추가하는 등 태그에 맞춤 속성을 추가할 수 있습니다.

다음 코드와 같이 id 검색과 동일한 작업을 수행하면 Python 변수에는 - 기호를 포함할 수 없다는 오류가 보고됩니다.


customattr = """
 <p data-custom="custom">custom attribute example</p>
   """
customsoup = BeautifulSoup(customattr,&#39;lxml&#39;)
customsoup.find(data-custom="custom")
# SyntaxError: keyword can&#39;t be an expression

이때, attrs 속성 값을 사용하여 사전 유형을 검색 매개변수로 전달합니다:


using_attrs = customsoup.find(attrs={&#39;data-custom&#39;:&#39;custom&#39;})
print using_attrs

CSS 클래스 기반 검색

CSS 클래스 속성의 경우 class는 Python의 키워드이므로 태그 속성 매개변수로 전달할 수 없습니다. 정의된 속성으로 자체 검색과 동일합니다. 또한 attrs 속성을 사용하여 일치를 위한 사전을 전달합니다.

attrs 속성을 사용하는 것 외에도 class_ 속성을 사용하여 전달할 수도 있는데, 이는 클래스와 다르며 오류가 발생하지 않습니다.


css_class = soup.find(attrs={&#39;class&#39;:&#39;producerlist&#39;})
css_class2 = soup.find(class_ = "producerlist")
print css_class
print css_class2

사용자 정의 함수 검색 사용

find() 메소드에 함수를 전달할 수 있습니다. 기능 정의에서 조건에 따라 검색합니다.

함수는 true 또는 false 값을 반환해야 합니다.


def is_producers(tag):
 return tag.has_attr(&#39;id&#39;) and tag.get(&#39;id&#39;) == &#39;producers&#39;
tag_producers = soup.find(is_producers)
print tag_producers.li.p.string

코드는 태그에 특정 id 속성이 있는지 여부와 조건이 충족되면 속성 값이 생산자와 같은지 확인하는 is_producers 함수를 정의합니다. true를 반환하고, 그렇지 않으면 false를 반환합니다.

다양한 검색 방법을 함께 사용

뷰티플수프는 다양한 검색 방법을 제공하며 마찬가지로 이러한 방법을 함께 사용하여 매칭을 수행하고 검색의 정확도를 높일 수도 있습니다. 경비.


combine_html = """
 <p class="identical">
  Example of p tag with class identical
 </p>
 <p class="identical">
  Example of p tag with class identical
 <p>
 """
combine_soup = BeautifulSoup(combine_html,&#39;lxml&#39;)
identical_p = combine_soup.find("p",class_="identical")
print identical_p

使用 find_all() 方法搜索

使用 find() 方法会从搜索结果中返回第一个匹配的内容,而 find_all() 方法则会返回所有匹配的项。

find() 方法中用到的过滤项,同样可以用在 find_all() 方法中。事实上,它们可以用到任何搜索方法中,例如:find_parents()find_siblings() 中 。


# 搜索所有 class 属性等于 tertiaryconsumerlist 的标签。
all_tertiaryconsumers = soup.find_all(class_=&#39;tertiaryconsumerlist&#39;)
print type(all_tertiaryconsumers)
for tertiaryconsumers in all_tertiaryconsumers:
 print tertiaryconsumers.p.string

find_all() 方法为 :


find_all(name,attrs,recursive,text,limit,**kwargs)

它的参数和 find() 方法有些类似,多个了 limit 参数。limit 参数是用来限制结果数量的。而 find() 方法的 limit 就是 1 了。

同时,我们也能传递一个字符串列表的参数来搜索标签、标签属性值、自定义属性值和 CSS 类。


# 搜索所有的 p 和 li 标签
p_li_tags = soup.find_all(["p","li"])
print p_li_tags
print
# 搜索所有类属性是 producerlist 和 primaryconsumerlist 的标签
all_css_class = soup.find_all(class_=["producerlist","primaryconsumerlist"])
print all_css_class
print

搜索相关标签

一般情况下,我们可以使用 find()find_all() 方法来搜索指定的标签,同时也能搜索其他与这些标签相关的感兴趣的标签。

搜索父标签

可以使用 find_parent() 或者 find_parents() 方法来搜索标签的父标签。

find_parent() 方法将返回第一个匹配的内容,而 find_parents() 将返回所有匹配的内容,这一点与 find() find_all() 方法类似。


# 搜索 父标签
primaryconsumers = soup.find_all(class_=&#39;primaryconsumerlist&#39;)
print len(primaryconsumers)
# 取父标签的第一个
primaryconsumer = primaryconsumers[0]
# 搜索所有 ul 的父标签
parent_ul = primaryconsumer.find_parents(&#39;ul&#39;)
print len(parent_ul)
# 结果将包含父标签的所有内容
print parent_ul
print
# 搜索,取第一个出现的父标签.有两种操作
immediateprimary_consumer_parent = primaryconsumer.find_parent()
# immediateprimary_consumer_parent = primaryconsumer.find_parent(&#39;ul&#39;)
print immediateprimary_consumer_parent

搜索同级标签

Beautiful Soup 还提供了搜索同级标签的功能。

使用函数 find_next_siblings() 函数能够搜索同一级的下一个所有标签,而 find_next_sibling() 函数能够搜索同一级的下一个标签。


producers = soup.find(id=&#39;producers&#39;)
next_siblings = producers.find_next_siblings()
print next_siblings

同样,也可以使用 find_previous_siblings() find_previous_sibling() 方法来搜索上一个同级的标签。

搜索下一个标签

使用 find_next() 方法将搜索下一个标签中第一个出现的,而 find_next_all() 将会返回所有下级的标签项。


# 搜索下一级标签
first_p = soup.p
all_li_tags = first_p.find_all_next("li")
print all_li_tags

搜索上一个标签

与搜索下一个标签类似,使用 find_previous()find_all_previous() 方法来搜索上一个标签。

위 내용은 Python이 Beautiful Soup 모듈을 사용하여 콘텐츠를 검색하는 방법에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.