본문 바로가기
Python 100제 따라하기/1. 웹스크래핑

(9) CSS Selector 활용하기 (2)

by 영거이 2022. 10. 13.
  • CSS 선택자 중에서 클래스 선택자와 id 선택자를 사용하는 방법을 이해한다.
  • 클래스 선택자는 ‘.’ 식별자로 나타내고, id선택자는 ‘#’ 식별자를 이용한다.
  • id 선택자와 class선택자를 쓰는 이유는 css에서 디자인할때 내용이 중복되거나 (class선택자 사용), 특정부분에만 디자인하고 싶을때 (id선택자 사용) 이름을 부여해서 디자인을 한다.
  • 아이디선택자는 id=’이름’ / css표시: #이름
  • 클래스선택자는 class=’이름’ / css표시: .이름
import requests
from bs4 import BeautifulSoup
#라이브러리를 불러온다.

url = "<https://en.wikipedia.org/wiki/Seoul_Metropolitan_Subway>"
resp = requests.get(url)
html_src = resp.text
soup = BeautifulSoup(html_src, 'html.parser')
#웹 페이지 문서의 HTML 소스코드를 파싱하여 BeautifulSoup 객체를 생성한다.
#변수 soup에 저장한다.

links = soup.select('a')
print(len(links))
print("\\n")
#BeautifulSoup의 select() 메소드는 예제 007에서 설명한 find_all() 메소드와 비슷하다.
#찾으려는 태그 이름을 매개변수로 전달하면, 웹문서에서 해당하는 모든 태그를 찾아서 리스트 형태로 리턴하기 때문이다.
#여기서는  태그를 모두 찾아서 변수 links에 저장한다.
#len() 함수로 확인하면, links 변수에는 1215개의 원소가 들어있다.  태그의 개수가 1215개라는 뜻이다.

print(links[:3])
print("\\n")
#앞에서 3개의 원소를 리스트 슬라이싱 기법으로 선택하고 출력해본다.

external_links = soup.select('a[class="external text"]')
print(external_links[:3])
print("\\n")
# 태그 중에서 class 속성을 갖고 그 값이 "external text"인 태그들을 찾아서 리스트로 리턴한다.
#리스트 슬라이싱으로 앞에서 3개의 원소만을 선택적으로 출력한다.

id_selector = soup.select('#siteNotice')
print(id_selector)
print("\\n")
#CSS의 id 선택자를 활용하는 방법이다.
#CSS스타일 시트에서 id는 고유한 값을 갖기 때문에 select() 메소드에 id선택자를 사용하면 오직 한 개의 태그만을 찾는다.
#id 선택자는 "#id속성값"으로 표현한다.
#예제의 '#siteNotice'는 id 속성값이 "siteNotice"인 태그를 가리킨다.

id_selector2 = soup.select('div#siteNotice')
print(id_selector2)
print("\\n")
#CSS의 id 선택자를 사용할 때, 특정 태그 안에서만 id 선택자를 찾는 방법이다.
#'div#siteNotice'는 div태그 중에서 id 속성값이 "siteNotice"인 div 태그를 뜻한다.

id_selector3 = soup.select('p#siteNotice')
print(id_selector3)
print("\\n")
#'p#siteNotice'는 p 태그 중에서 id 속성값이 "siteNotice"인 p 태그를 말한다.
#현재 웹 문서에서 id 속성값이 "siteNotice"인 태그는 앞서 확인한 div 태그가 유일하다.
#따라서 원소가 없는 빈 리스트가 출력된다.

class_selector = soup.select('.mw-headline')
print(class_selector2)
print("\\n")
#CSS의 클래스 선택자를 활용하는 방법이다.
#일반적으로 CSS 스타일 시트에서 서로다른 요소에 동일한 스타일을 지정할 때 클래스 선택자를 사용하는데,
#클래스선택자를 사용하면 같은 클래스를 갖는 여러 태그를 동시에 찾을 수 있다.
#클래스 선택자는 ".class속성값"으로 표현하는데, '.mw-headline'은 class 속성 값이 "mw-headline"에 해당하는 모든 태그를 뜻한다.

class_selector2 = soup.select('span.mw-headline')
print(class_selector2)
#클래스 선택자의 경우에도 특정 태그에 한정하여 적용할 수 있다.
#'span.mw-headline'은  태그 중에서 class 속성값이 "mw-headline"에 해당하는 태그를 뜻한다.

실행결과

 

1215

 

[<a id="top"></a>, <a class="mw-jump-link" href="#mw-head">Jump to navigation</a>, <a class="mw-jump-link" href="#searchInput">Jump to search</a>]

 

[<a class="external text" href="https://en.wikipedia.org/w/index.php?title=Seoul_Metropolitan_Subway&action=edit">improve it</a>, <a class="external text" href="https://deepl.com" rel="nofollow">DeepL</a>, <a class="external text" href="https://translate.google.com/" rel="nofollow">Google Translate</a>]

 

[<div id="siteNotice"><!-- CentralNotice --></div>]

 

[<div id="siteNotice"><!-- CentralNotice --></div>]

 

[]

 

[<span class="mw-headline" id="Overview">Overview</span>, <span class="mw-headline" id="History">History</span>, <span class="mw-headline" id="Lines_and_branches">Lines and branches</span>, <span class="mw-headline" id="Rolling_stock">Rolling stock</span>, <span class="mw-headline" id="Fares_and_ticketing">Fares and ticketing</span>, <span class="mw-headline" id="Current_construction">Current construction</span>, <span class="mw-headline" id="Opening_2022">Opening 2022</span>, <span class="mw-headline" id="Opening_2023">Opening 2023</span>, <span class="mw-headline" id="Opening_2024">Opening 2024</span>, <span class="mw-headline" id="Opening_2025+">Opening 2025+</span>, <span class="mw-headline" id="Approved_for_construction">Approved for construction</span>, <span class="mw-headline" id="Planned">Planned</span>, <span class="mw-headline" id="Seoul_City">Seoul City</span>, <span class="mw-headline" id="Incheon_City">Incheon City</span>, <span class="mw-headline" id="Network_map">Network map</span>, <span class="mw-headline" id="See_also">See also</span>, <span class="mw-headline" id="Notes">Notes</span>, <span class="mw-headline" id="References">References</span>, <span class="mw-headline" id="External_links">External links</span>]

 

[<span class="mw-headline" id="Overview">Overview</span>, <span class="mw-headline" id="History">History</span>, <span class="mw-headline" id="Lines_and_branches">Lines and branches</span>, <span class="mw-headline" id="Rolling_stock">Rolling stock</span>, <span class="mw-headline" id="Fares_and_ticketing">Fares and ticketing</span>, <span class="mw-headline" id="Current_construction">Current construction</span>, <span class="mw-headline" id="Opening_2022">Opening 2022</span>, <span class="mw-headline" id="Opening_2023">Opening 2023</span>, <span class="mw-headline" id="Opening_2024">Opening 2024</span>, <span class="mw-headline" id="Opening_2025+">Opening 2025+</span>, <span class="mw-headline" id="Approved_for_construction">Approved for construction</span>, <span class="mw-headline" id="Planned">Planned</span>, <span class="mw-headline" id="Seoul_City">Seoul City</span>, <span class="mw-headline" id="Incheon_City">Incheon City</span>, <span class="mw-headline" id="Network_map">Network map</span>, <span class="mw-headline" id="See_also">See also</span>, <span class="mw-headline" id="Notes">Notes</span>, <span class="mw-headline" id="References">References</span>, <span class="mw-headline" id="External_links">External links</span>]

 

해당 예제를 통해 실무에서…

  • 원하는 선택자와 태그를 정하여 특정부분의 html만 불러올 수 있다.

댓글