<aside> 💡 링크 수집을 하면서 자바스크립트로 이루어진 페이지를 렌더링하여 데이터를 추출할 필요가 생겼다. 렌더링을 도와주는 크롤링툴을 비교하여 최적화된 방식을 탐색해보자
</aside>
드라이버 설치와 관리가 다소 까다롭기 때문에, docker container를 설치하여 드라이버를 실행하도록 한다.
Installation
# pull selenium image
docker pull selenium/standalone-chrome
# run selenium container
docker container run -d --name selenium \\
-p 4444:4444 selenium/standalone-chrome-debug
위와 같이 설정할 경우 localhost:4444/wd/hub
로 접근할 수 잇다.
Usage
크롬 드라이버의 옵션을 바꿔가며 실행할 수 있다. 현재는 제목을 띄우는 것을 목적으로 한다.
몇가지 옵션에 대해서 살펴보자
--no-sandbox
: sandbox는 chromium의 보안을 담당하는 프로그램으로, chromium과 같이 거대하고 다양한 코드베이스 프로그램의 안전성을 위해서 도입되었다.
→ 굳이 코어한 영향을 끼지치는 않은 것으로 보인다. (RCE 위험성과 관련된 보안을 제공하는 것으로 보인다.)
→ 참고자료: https://no-sandbox.io/
--disable-dev-shm-usage
: 드라이버가 공유 메모리인 /dev/shm
을 사용하지 않겠다는 옵션이다.
from selenium import webdriver
from selenium.webdriver.common.by import By
url = "target_url"
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
driver = webdriver.Remote(
command_executor="<http://localhost:4444/wd/hub>",
options=chrome_options,
)
driver.get(url)
driver.implicitly_wait(2)
title = driver.find_element(By.CSS_SELECTOR , "target_path")
print(title.text)
결과 분석
url: https://boundless-outrigger-885.notion.site/b7c6f06ec2e44080a88bd4d1e35abd55
css_selector: #notion-app > div > div.notion-cursor-listener > div > div.notion-frame > div.notion-scroller.vertical.horizontal > div.whenContentEditable > div:nth-child(2) > div > div:nth-child(1) > div > div:nth-child(2) > div > div
결과: 3.3s로 예상보다 빠르다.
CPU의 메모리를 약 1GB 차지하는 것을 볼 수 있다.
javascript 코드의 렌더링을 도와주는 가벼운 브라우저, 컨테이너를 올리고 요청을 컨테이너에 타겟 url을 보내어 대신 javascript 코드를 렌더링 하는 것을 도와준다.
Installation
# pull splash iamge
docker pull scrapinghub/splash
# run splash container
docker container run -d --name splash -p 8050:8050 --rm scrapinghub/splash
Usage
import requests
from bs4 import BeautifulSoup
splash_url = "<http://localhost:8050/render.html>"
url = "<https://domain.you.want.com>"
r = requests.get(splash_url, params={"url": url , "wait": 2})
soup = BeautifulSoup(r.text, "html.parser")
결과 분석
소요시간이 약 10초로 매우 느리다!
원인
AngularJS로 작성한 코드에서 잘 작동하지 않을 수 있다고 하는데... 정확한 원인은 파악이 힘들다. → FAQ 바로가기
느려도 확실한 셀레니움을 사용하는 것이 좋을 수도...