Notice
Recent Posts
Recent Comments
Link
터칭 데이터
스크래핑할 요소의 타게팅 - ID & Class 본문
2-3. HTML의 Locator로 원하는 요소 찾기¶
- BeautifulSoup을 이용해서 더 정확하게 우리가 원하는 정보를 가져오는 방법을 학습해봅시다.
그래, 바로 너! id
와 class
¶
태그는 자신의 이름 뿐만 아니라 고유한 속성 또한 가질 수 있습니다.
이 중에서 id
와 class
는 Locator로서, 특정 태그를 지칭하는 데에 사용됩니다.
tagname
: 태그의 이름id
: 하나의 고유 태그를 가리키는 라벨class
: 여러 태그를 묶는 라벨
<p>This element has only tagname</p>
<p id="target">This element has tagname and id</p>
<p class="targets">This element has tagname and class</p>
id
와 class
를 이용해서 HTML의 특정 태그를 지칭하고 가져오는 방법에 대해서 알아봅시다.
In [1]:
# 스크래핑에 필요한 라이브러리를 불러와봅시다.
import requests
from bs4 import BeautifulSoup
또 다른 연습 사이트를 이용해봅시다.¶
In [3]:
res = requests.get("http://example.python-scraping.com/")
soup = BeautifulSoup(res.text, "html.parser")
id
를 이용해서 요소 가져오기¶
id
는 요소 하나를 지칭하는 특별한 별명입니다. (겹칠 수 없어요!)
id
를 이용하면 해당하는 태그 단 하나를 쉽게 가져올 수 있습니다.
In [4]:
## id 없이 div 태그를 찾아봅시다.
soup.find("div")
Out[4]:
<div align="center"> <h3>Error. Page cannot be displayed. Please contact your service provider for more details. (17)</h3> <!--- 1.241.75.157---> </div>
In [5]:
## id가 results인 div 태그를 찾아봅시다.
soup.find("div", id="results")
class
를 이용해서 요소(들) 가져오기¶
class
는 유사한 요소들을 구분짓는 별명입니다.
class
를 이용하면 해당하는 태그 단 하나를 쉽게 가져올 수 있습니다.
e.g. 차트 속의 데이터 등
In [6]:
# class가 "page-header"인 div 태그를 찾아봅시다.
soup.find("div", "page-header")
이는 객체이므로 다음과 같은 접근을 진행할 수 있겠죠?
In [8]:
# 위 결과에서 text 값을 깔끔하게 가져와봅시다.
find_result = soup.find("div", "page-header")
find_result
find_result.h1.text.strip() # 현재 예시 사이트가 비정상으로 에러
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[8], line 5 3 find_result = soup.find("div", "page-header") 4 find_result ----> 5 find_result.h1.text.strip() AttributeError: 'NoneType' object has no attribute 'h1'
'웹 스크래핑(Web scraping)' 카테고리의 다른 글
Selenium의 기초 WebDriver (0) | 2023.10.26 |
---|---|
요청시 헤더의 수정과 페이지네이션(Pagination) (0) | 2023.10.25 |
스크래핑할 요소의 타게팅 - 태그 (0) | 2023.10.25 |
파싱과 스크래핑의 기본, BeautifulSoup (0) | 2023.10.25 |
requests 라이브러리 (0) | 2023.10.24 |