[python] #6. BeautifulSoup - find_all (2)

exoluse·2021년 10월 12일
0

python - web crawling

목록 보기
7/20
post-thumbnail

이번 포스팅은

태그 내의 텍스트만 가지고 컨트롤해 볼 예정이다.

find_all 의 text 인자

text 값에 해당하는 엘리먼트를 리턴한다.

import requests
from bs4 import BeautifulSoup

html = """
<html><head><title>exoluse's velog1</title></head>

<body>
<p tag="Nana" class="title"><b>exoluse's velog2</b></p>
<b tag="Baba" class="vel">exoluse's velog3</b>
</body>

</html>

"""

soup = BeautifulSoup(html, "html.parser")

selected = soup.find_all(text="exoluse's velog1")
print(selected)

<!-- 결과 : 텍스트 값과 일치하는 엘리먼트의 텍스트를 리턴한다. -->
["exoluse's velog1"]

텍스트로 Like 검색을 해보자.

  1. 최상단에 re(정규표현식... 인가?) 를 import 하자.
import re
  1. 텍스트의 일부가 되는 문자열을 입력

html = """
<html><head><title>exoluse's velog1</title></head>

<body>
<p tag="Nana" class="title"><b>exoluse's velog2</b></p>
<b tag="Baba" class="vel">exoluse's velog3</b>
</body>

</html>

"""

soup = BeautifulSoup(html, "html.parser")

selected = soup.find_all(text=re.compile("exoluse"))
print(selected)

<!-- 결과 : exoluse가 들어간 모든 엘리먼트의 텍스트를 리턴한다. -->
["exoluse's velog1", "exoluse's velog2", "exoluse's velog3"]

여러 텍스트로 검색

html = """
<html><head><title>exoluse's velog1</title></head>

<body>
<p tag="Nana" class="title"><b>exoluse's velog2</b></p>
<b tag="Baba" class="vel">exoluse's velog3</b>
</body>

</html>

"""

soup = BeautifulSoup(html, "html.parser")

selected = soup.find_all(text=(["exoluse's velog1", "exoluse's velog2"]))
print(selected)

<!-- 결과 : 텍스트 배열과 일치하는 엘리먼트의 텍스트를 리턴한다.  -->
["exoluse's velog1", "exoluse's velog2"]

태그+텍스트 혼합 검색

html = """
<html><head><title>exoluse's velog1</title></head>

<body>
<p tag="Nana" class="title"><b>exoluse's velog2</b></p>
<b tag="Baba" class="vel">exoluse's velog3</b>
</body>

</html>

"""

soup = BeautifulSoup(html, "html.parser")

selected = soup.find_all("b", text=(["exoluse's velog1", "exoluse's velog2"]))
print(selected)

<!-- 결과 : b태그 이면서 텍스트가 일치하는 "엘리먼트"를 리턴한다. -->
[<b>exoluse's velog2</b>]

흠.....................

리턴되는 엘리먼트가 엄청 많을 경우는

limit 인자를 이용하도록 하자.

html = """
<html><head><title>exoluse's velog1</title></head>

<body>
<p tag="Nana" class="title"><b>exoluse's velog2</b></p>
<b tag="Baba" class="vel">exoluse's velog3</b>
</body>

</html>

"""

soup = BeautifulSoup(html, "html.parser")

selected = soup.find_all(text=re.compile("exoluse"), limit=1)
print(selected)


<!-- 결과 : 첫 1개만 리턴된다. -->
["exoluse's velog1"]

가면 갈수록

정리가 안되는 느낌이다. 카테고리별로 정리할 필요성을 느낀다. 끝

0개의 댓글