
๋ฆฌ์กํธ์ JS๋ง ์ฌ์ฉํ๋ค๋ณด๋ ์ฌ์ด๋ ์ธ์ด๋ ํ ๋ฒ ๊ณต๋ถํด๋ณด๊ณ ์ถ์ด์ Python์ ๋ฐฐ์ฐ๊ธฐ ์์ํ ์ด์ ๋ ์์ง๋ง , ํญ์ ์๋ ๋ก๊ทธ์ธ์ ์ด๋ป๊ฒ ๋๋๊ฑฐ์ง? ๋ธ๋ผ์ฐ์ ๊ฐ ์์์ ์์ง์ผ ๋ฐฉ๋ฒ์ ์๋? ์ด๋ฐ ์๋ฌธ์ ํ๊ณ ์์๊ธฐ ๋๋ฌธ์ ํฌ๋กค๋ง, ์๋ํ์ ๋ํด ๋ฐฐ์ฐ๊ณ ์ถ์๋ค. ๊ทธ๋์ ์์ํ Python์ผ๋ก ํฌ๋กค๋ง ํ๊ธฐ ๐ค๐ปโจ
๊ทธ๋ ๋ค๋ฉด ํฌ๋กค๋ง์ ํ์์ฑ์ ๋ฌด์์ผ๊น?๐ค
์๋ฅผ๋ค์ด, ํด๋ํฐ ์ผ์ด์ค๋ฅผ ๊ตฌ๋งคํ๋ ค๋ ์ํฉ์ด๋ค. ์ธํฐ๋ท์ผ๋ก ์ฌ๊ณ ์ถ์ ์ผ์ด์ค์ ๊ฐ๊ฒฉ์ ๋น๊ตํ๊ธฐ ์ํด "์ด๋ฆ" , "๊ฐ๊ฒฉ" , "๊ตฌ์ ์ฒ ๋งํฌ"๋ฅผ ์ ๋ฆฌ ํ๋ ค๊ณ ํ๋ค. ์ฌ๊ณ ์ถ์ ์ผ์ด์ค๊ฐ 30๊ฐ์ธ๋ฐ .. ์ด ์ผ์ด์ค๋ค์ ์ด๋ฆ, ๊ฐ๊ฒฉ, ๊ตฌ์ ์ฒ ๋งํฌ๋ฅผ ํ ๋ฒ์ ๊ฐ์ ธ์ฌ ๋ฐฉ๋ฒ์ ์์๊น? ํ ๋ ํฌ๋กค๋ง์ด ํ์ํ๋ค.
requests + BeautifulSoup
๊ธฐ์
์ ์ฃผ์ ํ์ฌ๊ฐ ๋ฑ ์ฃผ์์ ๋ณด๋ฅผ ์ป๊ธฐ ์ํด ๋ค์ด๋ฒ์ ์ฆ๊ถ ํ์ด์ง๋ฅผ ๋ณด๋ฉด ํ๋ฒ์ ์ ๋ณด๋ฅผ ์ป์ ์ ์๋ค. ์ด์๊ฐ์ด ํ ํ์ด์ง ์์ ์ํ๋ ์ ๋ณด๋ฅผ ์์งํ ์ ์๋๊ฒ ์ ์ ํฌ๋กค๋ง์ด๋ค.selenium
๋ก๊ทธ์ธ์ ํ๊ธฐ ์ํด์ ๋ก๊ทธ์ธ ๋ฒํผ์ ๋จผ์ ๋๋ฌ์ผ ์์ด๋์ ๋น๋ฐ๋ฒํธ๋ฅผ ์
๋ ฅํ ์ ์๋ ํ์ด์ง๋ก ์ด๋์ ํ๋ค. ๋ฐ๋ผ์ ์ด๋ ๊ฒ ํ์ด์ง ์ด๋์ด ์์ด์ผ ์ ๋ณด๊ฐ ๋๋ฌ๋๋ ๋์ ๋ฐ์ดํฐ๋ฅผ ์์งํ๋ ๋ฐฉ๋ฒ์ด ๋์ ํฌ๋กค๋ง์ด๋ค.requestsimport requests response= requests.get("http://www.naver.com") html= response.text print(html)
์ด๋ ๊ฒ requests๋ฅผ ์ด์ฉํ์ฌ http://www.naver.com ์ ๋ถ๋ฌ์ค๋ฉด, ํฐ๋ฏธ๋์๋ ๋ค์ด๋ฒ ๋ฉ์ธํ์ด์ง ์ html ์์ค์ฝ๋๊ฐ ์ถ๋ ฅ๋๋ค.
BeautifulSoupimport requests from bs4 import BeautifulSoup response= requests.get("https://www.naver.com") html= response.text soup = BeautifulSoup(html, "html.parser") word=soup.select_one("#topAsideArea") print(word)
soup = BeautifulSoup(html, "html.parser") ๊ตฌ๋ฌธ์ requests๋ก ๋ถ๋ฌ์จ html ์ฝ๋๊ฐ ๋ฌธ์์ด์ด๊ธฐ ๋๋ฌธ์ ํ์ฑํ๊ธฐ ์ด๋ ค์์ "html.parser" ์ด๋ผ๋ html ๋ฒ์ญ ์ ์๋์ ์ฌ์ฉํ์ฌ ์ฝ๊ฒ ๋ง๋ค์ด์ค ํ, soup์ ๋ด๋๋ค.
word=soup.select_one("#topAsideArea") ๊ตฌ๋ฌธ์์ #topAsideArea ์ ๋ค์ด๋ฒ ๋ฉ์ธํ์ด์ง์ ๋ฉ๋ด ๋ถ๋ถ id๊ฐ์ด๋ค. ์ ๊ตฌ๋ฌธ์ ํตํด id๊ฐ์ด ์ํ html ์ฝ๋๋ฅผ ๊ฐ์ ธ์์ ํฐ๋ฏธ๋์ ์ถ๋ ฅ๋๋ค.
seleniumfrom selenium import webdriver from selenium.webdriver.chrome.service import Service from selenium.webdriver.chrome.options import Options #ํฌ๋กฌ ๋๋ผ์ด๋ฒ ์๋ ์ ๋ฐ์ดํธ from webdriver_manager.chrome import ChromeDriverManager # ๋ธ๋ผ์ฐ์ ๊บผ์ง ๋ฐฉ์ง chrome_options = Options() chrome_options.add_experimental_option("detach",True) service = Service(executable_path=ChromeDriverManager().install()) driver = webdriver.Chrome(service=service, options=chrome_options) driver.get("https://www.naver.com")
์ ์ฝ๋์ ์ฒ์ 4์ค์ selenium ๊ธฐ๋ณธ์ค์ ์ด๋ค.
service = Service(executable_path=ChromeDriverManager().install()) , driver = webdriver.Chrome(service=service,options=chrome_options) ์ ChromeDriverManager๋ฅผ ํตํด์ ํฌ๋กฌ ๋๋ผ์ด๋ฒ๋ฅผ ์๋์ผ๋ก ์ค์นํ๋ค๋ ์๋ฏธ์ด๋ค.
์๋์ผ๋ก ๋ธ๋ผ์ฐ์ ๋ฅผ ๋์ฐ๊ธฐ ์ํ์ฌ ์ด๋ ๊ฒ driver.get("https://www.naver.com") ๋์ธ ๋ธ๋ผ์ฐ์ ์ ์ฃผ์๋ฅผ ์ ์ด์ค์ผ ํ๋ค.
๐จ ์ฝ๋๋ฅผ ์คํ์์ผฐ์ ๋ ๋ธ๋ผ์ฐ์ ๊ฐ ์ ์คํ๋๋๊ฐ ์ถ๋ค๊ฐ ๊บผ์ ธ๋ฒ๋ฆฌ๋ ๊ฒฝ์ฐ๊ฐ ์๋ค. ์ด ๋ ์ค์ ์คํํ๋ฉด ๋ธ๋ผ์ฐ์ ๊บผ์ง ํ์์ ๋ฐฉ์งํ ์ ์๋ค. chrome_options = Options() , chrome_options.add_experimental_option("detach",True)