[Python] ํฌ๋กค๋ง(Crawling)
๐ ๋ค์ด๊ฐ๋ฉฐ
์ด๋ฒ ๊ธ์์๋ ํฌ๋กค๋ง(Crawling)์ผ๋ก ์น ๋ฐ์ดํฐ๋ฅผ ์์งํ๋ค. ๋ค์ ๋ด์ค ํค๋๋ผ์ธ๊ณผ ๋ก๋ ๋ฒํธ๋ฅผ ๊ฐ์ ธ์ ๋ฐ์ดํฐํ๋ ์์ผ๋ก ๋ง๋ค๊ณ ์๊ฐํ๊น์ง ํด๋ณธ๋ค.
ํฌ๋กค๋ฌ(crawler): ์๋ํ๋ ๋ฐฉ๋ฒ์ผ๋ก ์น์ ํ์ํ๋ ํ๋ก๊ทธ๋จ. ์น์ ํ๋ ๊ฒ์ด ์น ํฌ๋กค๋ง, ๊ทธ ๋ฐ์ดํฐ๋ฅผ ์์งํ๋ ๊ฒ์ด ๋ฐ์ดํฐ ํฌ๋กค๋ง์ด๋ค.
ํฌ๋กค๋ง์ ๊ธฐ๋ณธ ํ๋ฆ:
1
โ URL ์ ์ โ โก requests.get()์ผ๋ก ์์ฒญ โ โข BeautifulSoup์ผ๋ก HTML ๋ณํ โ โฃ select()๋ก ์ํ๋ ํ๊ทธ ์ ๋ณ
1. ๋ด์ค ํค๋๋ผ์ธ ํฌ๋กค๋ง
1
2
3
4
5
6
7
8
# ๋ค์ ๋ด์ค ํ์ด์ง ํฌ๋กค๋ง
url = 'https://news.daum.net/'
resp = requests.get(url) # โก ์์ฒญ
html = BeautifulSoup(resp.text, 'html.parser') # โข HTML ๋ณํ
for news in html.select('a.link_txt')[:-13]: # โฃ ํ๊ทธ ์ ๋ณ
print(news.text.strip().replace('[', '').replace(']', ''))
๐ก ๊ฐ๋ฐ์ ๋ชจ๋๋ก ์ํ๋ ์์์ ํ๊ทธ(
a.link_txt)๋ฅผ ํ์ธํดselect()์ ๋ฃ๋๋ค..text.strip()์ผ๋ก ํ ์คํธ๋ง ์ถ์ถํ๊ณ.replace()๋ก ๋ถํ์ํ ๋ฌธ์๋ฅผ ์ ๋ฆฌํ๋ค.
2. ๋ก๋ ๋ฒํธ ํฌ๋กค๋ง (1~30ํ์ฐจ)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
lotto_list = []
for i in range(1, 31):
print(f'{i}ํ์ฐจ ํฌ๋กค๋ง ์ค์
๋๋ค.')
# ์ฐจ๋จ ๋ฐฉ์ง (๋๋ค ๋๋ ์ด)
seed = np.random.randint(100)
np.random.seed(seed)
time.sleep(np.random.randint(5))
url = f'https://search.daum.net/search?w=tot&DA=LOT&q={i}ํ์ฐจ%๋ก๋'
resp = requests.get(url)
html = BeautifulSoup(resp.text, 'html.parser')
for ball_nm in html.select('span.ball')[:6]:
lotto_list.append(int(ball_nm.text))
print('ํฌ๋กค๋ง ์๋ฃ!!!')
โ ๏ธ ๋ฐ๋ณต ์์ฒญ ์ ์ฐจ๋จ(block)์ ํผํ๊ธฐ ์ํด ๋๋ค ๋๋ ์ด(
time.sleep)๋ฅผ ์ค๋ค. ๋ชจ๋ ๋ฒํธ๋ฅผ ํ๋์ ๋ฆฌ์คํธ์ ๋ด๋ ์ด์ ๋, ์ดํreshape์ผ๋ก ๋ฐ์ดํฐํ๋ ์์ ๋ง๋ค๊ธฐ ์ํจ์ด๋ค.
3. ๋ฐ์ดํฐํ๋ ์ ๋ณํ
1
2
3
4
lotto = np.array(lotto_list).reshape(-1, 6) # 6๊ฐ์ฉ ๋ฌถ์ด ํ์ฐจ๋ณ ํ์ผ๋ก
index_list = [f'{i}ํ์ฐจ' for i in range(1, 31)]
df = pd.DataFrame(lotto, index=index_list)
df
๐ก
reshape(-1, 6)์ โ์ด์ 6๊ฐ๋ก ๊ณ ์ , ํ์ ์๋ ๊ณ์ฐโ์ด๋ผ๋ ๋ป. ๋ฆฌ์คํธ๋ฅผ ํ์ฐจ๋ณ 6๊ฐ ๋ฒํธ์ ํ๋ก ์ฌ๊ตฌ์ฑํ๋ค.
4. ์๊ฐํ
1
2
3
4
5
6
import seaborn as sns
import matplotlib.pyplot as plt
plt.figure(figsize=(12, 6))
sns.countplot(lotto_list) # ๋ฒํธ๋ณ ์ถํ ๋น๋
plt.show()
countplot์ผ๋ก ๊ฐ ๋ฒํธ์ ๋น์ถ์ ํ์ธํ ์ ์๋ค.
๐ก ๋ฒํธ๋ณ ํธ์ฐจ๊ฐ ํฐ ๊ฒ์ ํ๋ณธ์ด 30ํ์ฐจ๋ฟ์ด๊ธฐ ๋๋ฌธ์ด๋ค. ํ์ฐจ๊ฐ ๊ธธ์ด์ง์๋ก ํต๊ณ์ ํ๋ฅ (๊ท ๋ฑ)์ ๊ฐ๊น์์ง ๊ฒ์ด๋ค.
๐ ์ ๋ฆฌ
1
2
3
4
5
6
ํฌ๋กค๋ง ํ๋ฆ
โโ ์์ฒญ requests.get(url)
โโ ํ์ฑ BeautifulSoup(resp.text, 'html.parser')
โโ ์ ๋ณ html.select('ํ๊ทธ')
โโ ์ฐจ๋จ ๋ฐฉ์ง time.sleep()์ผ๋ก ๋๋ค ๋๋ ์ด
โโ ๊ฐ๊ณต/์๊ฐํ reshape โ DataFrame โ countplot
| ๋๊ตฌ | ์ญํ |
|---|---|
| requests | URL์ ๋ฐ์ดํฐ ์์ฒญ |
| BeautifulSoup | HTML ํ์ฑ |
| select() | CSS ์ ํ์๋ก ํ๊ทธ ์ถ์ถ |
| reshape/DataFrame | ์์ง ๋ฐ์ดํฐ๋ฅผ ํ๋ก |
ํฌ๋กค๋ง์ โ์์ฒญ โ ํ์ฑ โ ์ ๋ณโ์ ๋จ์ํ 3๋จ๊ณ ํ๋ฆ์ด๋ค. ์ฌ๊ธฐ์ ์ฐจ๋จ ๋ฐฉ์ง(๋๋ ์ด)์ ๋ฐ์ดํฐ ๊ฐ๊ณต(DataFrame)์ ๋ํ๋ฉด ์ค์ฉ์ ์ธ ๋ฐ์ดํฐ ์์ง ํ์ดํ๋ผ์ธ์ด ์์ฑ๋๋ค.



Comments powered by Disqus.