BeautifulSoup
โข
ํ์ฑ์ ๋์์ฃผ๋ ๊ฐ๋ ฅํ python ๋ผ์ด๋ธ๋ฌ๋ฆฌ
โข
์ฝ๊ณ ๊ฐ๊ฒฐํ๋ฉฐ, ์ ๊ท์์ ์์ฑํ ํ์ ์์ด tag, id, class ๋ฑ์ ์ด๋ฆ์ผ๋ก ์ฝ๊ฒ ํ์ฑ ๊ฐ๋ฅ
โข
์ค์น: pip install beautifulsoup4
์ฃผ์ ํจ์
์ฃผ์ ๊ธฐ๋ฅ | ์ค๋ช
|
find_all(ํ๊ทธ) | ํ๊ทธ๊ฐ ํฌํจ๋์ด ์๋ ๋ชจ๋ ๋ฌธ์ฅ ๋ฐํ |
find(ํ๊ทธ) | ํ๊ทธ๊ฐ ํฌํจ๋์ด ์๋ ๋ชจ๋ ๋ฌธ์ฅ ์ค ๊ฐ์ฅ ์ฒซ๋ฒ์งธ ๋ฌธ์ฅ ๋ฐํ |
select(์ ํ์) | ์ ํ์(selector)๋ฅผ ์ฌ์ฉํ ๋ฐ์ดํฐ์ ํ |
์ฌ์ฉ ๋ฐฉ๋ฒ
find_all(), find()
from bs4 import BeautifulSoup
# โฆ html ๊ฐ์ ธ์ค๋ ๋ถ๋ถ ์๋ต โฆ
soup = BeautifulSoup(html, 'lxmlโ)
#1. ํฌ์คํธ ๋ฆฌ์คํธ
post_list = soup.find_all('div', {'class': 'post-preview'})
#2. ์ ๋ชฉ, ์์ ๋ชฉ, ๋ ์ง ๋ฆฌ์คํธ
for post in post_list:
title = post.find('h2', {'class' : 'post-title'}).text.strip()
Python
๋ณต์ฌ
selector()
# ์ฝ๋ ์๋ต
selector = '#yesFixCorner > dl > dd > ul.yesCornerLi > li:nth-child(1) > a'
data = soup.select(selector)
Python
๋ณต์ฌ
Tag ํ์ธ ๋ฐฉ๋ฒ
โข
๋ง์ฐ์ค ์ฐํด๋ฆญ > Copy > Copy element ๋๋ Copy Selector ๋ฑ ์ํฉ์ ๋ฐ๋ผ ์ ์ ํ๊ฒ ์ฌ์ฉ
๋ฐ์ดํฐ ์ฒ๋ฆฌ ๋ฐฉ๋ฒ
<div class="post-preview">
<a href="index.html">
<h2 class="post-title">
๋จํ๊ตฌ๊ฒฝ๊ฐ์~~
</h2>
<h3 class="post-subtitle">
๋ํค๋ ๋จํ๊ตฌ๊ฒฝ ๋ค๋
์์ด์
</h3>
</a>
<p class="post-meta">September 24, 2021</p>
</div>
<hr>
<div class="post-preview">
<a href="index.html">
<h2 class="post-title">
๋ค์ด์ดํธ ์์!
</h2>
<h3 class="post-subtitle">
๊ฟ์ ์ด์ ๊ทธ๋ง, ๋ ์ฌํ ๊ณฐ๋์ด๋ก ๋ค์ ํ์ด๋๊ธฐ
</h3>
</a>
<p class="post-meta">June 18, 2021</p>
</div>
<hr>
HTML
๋ณต์ฌ
1.
posts ๋จ์๋ก ๊ด๋ฆฌ: ํฌ์คํ
(๊ธ) ๋จ์๋ก ์ชผ๊ฐ๊ธฐ
a.
2.
post ๋ถ์: ํ๋์ ํ๋์ ํฌ์คํ
์ ํฌํจ๋ ์ ๋ชฉ, ์์ ๋ชฉ, ๋ ์ง๋ฅผ ์ถ์ถํ๊ธฐ
[์ค์ต] yes24
[๊ณผ์ ์ค๋ช
]
๊ตญ๋ด๋์ ๋ฒ ์คํธ์
๋ฌ ์์ 1-10์ ์ฑ
์ ๋ํด
์์, ์ ๋ชฉ, ์ ์, ์ถํ์ฌ, ํ๋งค๊ฐ, ์ถ๊ฐ์ผ์ ํ๋ฆฐํธํ์์ค.
[์ถ๋ ฅ ์์]
1.
์ ๋ชฉ: ํธ๋ ๋ ์ฝ๋ฆฌ์ 2024, ์ ์: ๊น๋๋, ์ ๋ฏธ์, ์ต์งํ, ์ด์์ง, ๊ถ์ ์ค ์ธ 6๋ช
, ์ถํ์ฌ: ๋ฏธ๋์์ฐฝ, ํ๋งค๊ฐ: 17,100์, ์ถ๊ฐ์ผ: 2023๋
10์ 05์ผ
2.
........................
3.
........................
4.
....................
5.
...................
[์ค์ต] Tripadvisor
โข
โข
1.
์ฌ์ดํธ์ html์ ์ฝ์ด๋ค์ด๊ธฐ: requests.get(url) ์ฌ์ฉ
2.
ํ
์คํธ ํํ์ ๋ฐ์ดํฐ๋ฅผ html ํ๊ทธ๋ณ๋ก ๊ตฌ๋ถํ์ฌ ํ์ฑํ๊ธฐ : BeutifulSoup
3.
ํน์ ํ๊ทธ๊ฐ๋ง ์ฐพ๊ธฐ : findAll, find
4.
ํ์ํ ๋ฐ์ดํฐ๊ฐ ์ ์ ํ๊ธฐ
5.
๊ด๊ณ ์ํ ์ ๊ฑฐํ๊ธฐ
6.
๋ฐ์ดํฐํ๋ ์ ํํ๋ก ๋ง๋ค๊ธฐ
[๊ณผ์ ] ์ฟ ํก
1.
์ฌ์ดํธ์ html์ ์ฝ์ด๋ค์ด๊ธฐ: requests.get(url) ์ฌ์ฉ
โข
ํค๋ ์ค์ : http://www.useragentstring.com/
โข
url ์ฃผ์(GET ๋ฐฉ์) ํ์์ ์ดํดํ๊ธฐ
2.
ํ
์คํธ ํํ์ ๋ฐ์ดํฐ๋ฅผ html ํ๊ทธ๋ณ๋ก ๊ตฌ๋ถํ์ฌ ํ์ฑํ๊ธฐ : BeutifulSoup
3.
ํน์ ํ๊ทธ๊ฐ๋ง ์ฐพ๊ธฐ : findAll, find
4.
ํ์ํ ๋ฐ์ดํฐ๊ฐ ์ ์ ํ๊ธฐ
โข
๊ด๊ณ ์ํ ์ ๊ฑฐํ๊ธฐ
5.
๋ฐ์ดํฐ ์ ์ฅํ๊ธฐ
โข
csv ํ์์ผ๋ก ์ ์ฅํ๊ธฐ