์ ๋ง ์ค๋๋ง์ ๋ธ๋ก๊ทธ๋ฅผ ์ฐ๋ ๊ฑฐ ๊ฐ๋ค. ํ๊ณ๋ฅผ ๋๋ณด์๋ฉด ์์ฆ ์ ๋ณด์ฒ๋ฆฌ๊ธฐ์ฌ ํ๊ธฐ ์ํ, ๊ฐ์ธ ํฌํธํด๋ฆฌ์ค ์ค๋น, ์กธ์ ์ค๋น ๋ฑ๋ฑ์ผ๋ก ๋ง์ด ์๊ฐ์ด ์์๋ค. ์ํผ ! ์ด๋ฒ ์๊ฐ์๋ ํฌ๋กค๋ง์ด๋ค. ํฌ๋กค๋ง์ ๊ด์ฌ์ด ์์ด์ ๊ด๋ จ ๋ด์ฉ์ ์ธํฐ๋ท์ ์ฐพ์๋ณด๋ฉฐ ๊ณต๋ถํ๋ค๊ฐ ์๊ฒ ๋ ๋ด์ฉ๊ณผ ์ค๋ฅ, ๋ด๊ฐ ์์ ํ ๋ถ๋ถ์ ์จ๋ณด๋ ค๊ณ ํ๋ค.
๋จผ์ ๋ด๊ฐ ์ฐธ๊ณ ํ ๋ธ๋ก๊ทธ์ ์ถ์ฒ๋ฅผ ๋จ๊ธฐ๊ฒ ๋ค.
https://well-made-codestory.tistory.com/33#03
[Web Crawling] ์ ๊ตญ ๋ํ๊ต ์ด๋ฆ ํฌ๋กค๋ง ํ์ฌ DB์ ์ ์ฅํ๊ธฐ -1
์ ๊ตญ ๋ํ๊ต ์ด๋ฆ์ ํฌ๋กค๋ง ํ์ฌ DB์ ์ ์ฅํ๊ธฐ -1 ๊ฐ์ Toy Project์์ ์ฌ์ฉํ๊ธฐ ์ํด ์ ๊ตญ์ ๋ํ๊ต๋ฅผ ๋ฏธ๋ฆฌ ์ ์ฅํ์ฌ DB์ ์ ๋ฆฌํ๊ณ , ์ด๋ฅผ ํ์๊ฐ์ ์์ ์ ์ฅ๋ DB๋ฅผ ๋ฏธ๋ฆฌ ๋ ธ์ถ ์์ผ ํต์ผ๋ ์์์ผ
well-made-codestory.tistory.com
1 2 | import cloudscraper from bs4 import BeautifulSoup | cs |
cloudscraper๋ ํฌ๋กค๋งํ ๋ ํด๋ผ์ฐ๋ ๋ณดํธ๋ฅผ ์ฐํํด์ฃผ๊ธฐ ์ํ ๊ธฐ๋ฅ์ ์ ๊ณตํด์ฃผ๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ด๋ค.
BeautifulSoup๋ HTML์ด๋ XML์์ ์ํ๋ ์ ๋ณด๋ฅผ ํ์ฑํ ๋ ํ์ํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์ด๋ค.
1 2 3 4 5 6 7 8 | def get_html(url): #html ํ์ด์ง ๊ฐ์ ธ์ค๊ธฐ scraper = cloudscraper.create_scraper() html = "" g_html = scraper.get(url) if g_html.status_code == 200: html = g_html.text return html | cs |
์ด ๋ถ๋ถ์ html ํ์ด์ง๋ฅผ ๊ฐ์ ธ์ค๋ ๋ถ๋ถ์ด๋ค.
cloudscraper.create_scraper()๋ cloudscraper์ ๊ฐ์ฒด๋ฅผ ์์ฑํด์ฃผ๋ ๋ถ๋ถ์ด๋ค.
1 2 3 4 5 6 7 8 9 10 | def crawl_html(html): #๊ฐ์ ธ์จ html ํ์ด์ง์ tag ์ ์ ๋ณด ๊ฐ์ ธ์ค๊ธฐ u_list = [] soup_html = BeautifulSoup(html,'html.parser') title = soup_html.find_all('a', class_= "A4OyphEg") for t in title: tmp = t["title"] if '๋ชฉ๋ก' not in tmp: u_list.append(tmp) s_list = set(u_list) return s_list | cs |
์ด ๋ถ๋ถ์์ ํฌ๋กค๋ง์ ๋ณธ๊ฒฉ์ ์ผ๋ก ์ค์ํ๋ค. ๋จผ์ ๋น ๋ฆฌ์คํธ๋ฅผ ํ๋ ๋ง๋ค์ด ๋๋ค. ๊ทธ ๋ค์ BeautifulSoup ๊ฐ์ฒด๋ฅผ ํ๋ ๋ง๋ค์ด์ค๋ค. ๊ทธ ๋ค์ ๊ทธ ๊ฐ์ฒด์ find_all ๋ฉ์๋๋ฅผ ์ด์ฉํ์ฌ a ํ๊ทธ์ class๊ฐ "A40yphEg"์ธ ๊ฒ์ ๋ชจ๋ ๊ฐ์ ธ์จ๋ค. ์ฌ๊ธฐ์ ๋ด๊ฐ ์์ ํ ๊ฒ์ด ๋ฐ์์ด ๋๋๋ฐ ํด๋์ค๊ฐ ์ฃผ๊ธฐ์ ์ผ๋ก ๋ฐ๋๊ธฐ ๋๋ฌธ์ HTML์ ๋ณด๋ฅผ ํ์ธํด๋ณด๊ณ ํด๋์ค๋ฅผ ๋ฐ๊ฟ์ ์์ ์ ํด์ผ ํ๋ค.
๊ทธ๋ผ ์ด๋ ๊ฒ ์ถ๋ ฅ์ด ๋๋ค. ์ฐ๋ฆฌ๋ ์ก์ ๋ณด๋ฅผ ์ ๊ฑฐํด์ฃผ๊ณ ์ด๋ฆ๋ง์ ์ํ๋ค. ๊ทธ๋ ๊ธฐ ๋๋ฌธ์ title ์์ฑ๋ง์ ์ถ์ถํด์ ๊ฐ์ ธ์์ผ ํ๋ค.
ใฑ๊ทธ๋ฐ ๋ค์ ์ด ๋ฆฌ์คํธ๋ฅผ set()์ผ๋ก ์ค๋ณต๋ ๊ฒ์ ์ ๊ฑฐํด์ค๋ค. ๊ทธ๋ฐ ๋ค์ ์ด๊ฒ์ ๋ฆฌํดํด์ค๋ค.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import cloudscraper from bs4 import BeautifulSoup def get_html(url): #html ํ์ด์ง ๊ฐ์ ธ์ค๊ธฐ scraper = cloudscraper.create_scraper() html = "" g_html = scraper.get(url) if g_html.status_code == 200: html = g_html.text return html def crawl_html(html): #๊ฐ์ ธ์จ html ํ์ด์ง์ tag ์ ์ ๋ณด ๊ฐ์ ธ์ค๊ธฐ u_list = [] soup_html = BeautifulSoup(html,'html.parser') title = soup_html.find_all('a', class_= "A4OyphEg") for t in title: tmp = t["title"] if '๋ชฉ๋ก' not in tmp: u_list.append(tmp) s_list = set(u_list) return s_list html = get_html('https://namu.wiki/w/%EB%8C%80%ED%95%9C%EB%AF%BC%EA%B5%AD%EC%9D%98%20%EB%8C%80%ED%95%99%EA%B5%90%20%EB%AA%A9%EB%A1%9D') univ_list = crawl_html(html) univ_list = list(univ_list) univ_list.sort() for univ in univ_list: print(univ, end='\n') | cs |
์ ์ฒด ์ฝ๋์ด๋ค.
.