์›น ํฌ๋กค๋ง ๊ฐ„๋‹จ์˜ˆ์ œ | Beautiful Soup ์‚ฌ์šฉ๋ฒ•

2021. 4. 18. 03:11ใ†๐Ÿ’ป ๊ฐœ๋ฐœ/Python

์›น์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ํฌ๋กค๋งํ• ๋•Œ, Python ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์ธ Beautiful Soup์„ ํ†ตํ•ด ์›ํ•˜๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๋‹ค.

 

1. ์„ค์น˜ํ™˜๊ฒฝ

Python 3.6

 

2. BeautifulSoup ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์„ค์น˜

pip install beautifulsoup4

 

3. ๋‰ด์Šค๊ธฐ์‚ฌ ํฌ๋กค๋ง

IT์กฐ์„  ๋‰ด์Šค ๋ฉ”์ธํŽ˜์ด์ง€๋ฅผ ๋ณด๋ฉด, ๊ธฐ์‚ฌ๋“ค์ด ๋ชจ๋‘ ๋งํฌ๋กœ ๊ฑธ๋ ค์žˆ๋‹ค. ๊ธฐ์‚ฌ์˜ URL์„ ์ˆ˜์ง‘ํ•˜๊ธฐ ์œ„ํ•ด aํƒœ๊ทธ์—์„œ href๋ฅผ ๊ฐ€์ ธ์˜ค๋ฉด ๋œ๋‹ค. 

 

4. ํŒŒ์ด์ฌ ์ฝ”๋“œ 

from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://it.chosun.com/")

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

for link in bsObject.find_all('a'):
    print(link.text.strip(), link.get('href'))
  • urlopen์„ ์‚ฌ์šฉํ•˜์—ฌ ํ•ด๋‹น ํŽ˜์ด์ง€์˜ HTML์†Œ์Šค๋ฅผ ๊ฐ€์ ธ์˜จ๋‹ค
  • BeautifulSoup์„ ์‚ฌ์šฉํ•˜์—ฌ ํŒŒ์‹ฑํ•˜๊ธฐ
  • find_all(): ํ•ด๋‹น ์กฐ๊ฑด์— ๋งž๋Š” ๋ชจ๋“  ํƒœ๊ทธ๋“ค์„ ๊ฐ€์ ธ์™€, ๋ฆฌ์ŠคํŠธ๋กœ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค

 

5. ์‹คํ–‰๊ฒฐ๊ณผ