๋ฆฌ์กํธ์ JS๋ง ์ฌ์ฉํ๋ค๋ณด๋ ์ฌ์ด๋ ์ธ์ด๋ ํ ๋ฒ ๊ณต๋ถํด๋ณด๊ณ ์ถ์ด์ Python์ ๋ฐฐ์ฐ๊ธฐ ์์ํ ์ด์ ๋ ์์ง๋ง , ํญ์ ์๋ ๋ก๊ทธ์ธ์ ์ด๋ป๊ฒ ๋๋๊ฑฐ์ง? ๋ธ๋ผ์ฐ์ ๊ฐ ์์์ ์์ง์ผ ๋ฐฉ๋ฒ์ ์๋? ์ด๋ฐ ์๋ฌธ์ ํ๊ณ ์์๊ธฐ ๋๋ฌธ์ ํฌ๋กค๋ง, ์๋ํ์ ๋ํด ๋ฐฐ์ฐ๊ณ ์ถ์๋ค. ๊ทธ๋์ ์์ํ Python์ผ๋ก ํฌ๋กค๋ง ํ๊ธฐ ๐ค๐ปโจ
๊ทธ๋ ๋ค๋ฉด ํฌ๋กค๋ง์ ํ์์ฑ์ ๋ฌด์์ผ๊น?๐ค
์๋ฅผ๋ค์ด, ํด๋ํฐ ์ผ์ด์ค๋ฅผ ๊ตฌ๋งคํ๋ ค๋ ์ํฉ์ด๋ค. ์ธํฐ๋ท์ผ๋ก ์ฌ๊ณ ์ถ์ ์ผ์ด์ค์ ๊ฐ๊ฒฉ์ ๋น๊ตํ๊ธฐ ์ํด "์ด๋ฆ" , "๊ฐ๊ฒฉ" , "๊ตฌ์ ์ฒ ๋งํฌ"๋ฅผ ์ ๋ฆฌ ํ๋ ค๊ณ ํ๋ค. ์ฌ๊ณ ์ถ์ ์ผ์ด์ค๊ฐ 30๊ฐ์ธ๋ฐ .. ์ด ์ผ์ด์ค๋ค์ ์ด๋ฆ, ๊ฐ๊ฒฉ, ๊ตฌ์ ์ฒ ๋งํฌ๋ฅผ ํ ๋ฒ์ ๊ฐ์ ธ์ฌ ๋ฐฉ๋ฒ์ ์์๊น? ํ ๋ ํฌ๋กค๋ง์ด ํ์ํ๋ค.
requests + BeautifulSoup
selenium
requests
import requests response= requests.get("http://www.naver.com") html= response.text print(html)
์ด๋ ๊ฒ requests๋ฅผ ์ด์ฉํ์ฌ http://www.naver.com
์ ๋ถ๋ฌ์ค๋ฉด, ํฐ๋ฏธ๋์๋ ๋ค์ด๋ฒ ๋ฉ์ธํ์ด์ง
์ html ์์ค์ฝ๋๊ฐ ์ถ๋ ฅ๋๋ค.
BeautifulSoup
import 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 ์ฝ๋๋ฅผ ๊ฐ์ ธ์์ ํฐ๋ฏธ๋์ ์ถ๋ ฅ๋๋ค.
selenium
from 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)