Python Selenium을 이용해 웹브라우저의 백그라운드 요청 가져오기
Posted In: 미분류
Python을 이용해 데이터를 크롤링할 때 많이 쓰는 것 중에 하나가 Selenium입니다. Selenium을 이용하면 Chrome이나 Firefox를 코드상에서 실행하고 사용자 동작을 코드로 구현하여 사용자의 행동을 그대로 따라하도록 할 수 있습니다.
요즘은 Ajax나 Websocket을 이용해 백그라운드에서 요청을 하는 것이 많습니다. 가끔 그런 요청에서 넘어오는 데이터가 필요한 경우가 있는데 아쉽게도 Selenium에서는 백그라운드 요청내용을 가져오는 메소드가 없습니다.
Selenium-wire를 사용하면 Slenium의 기능을 그대로 사용하면서 백그라운드 요청 내용을 받아올 수 있습니다.
from seleniumwire import webdriver # Import from seleniumwire
# Create a new instance of the Firefox driver
driver = webdriver.Firefox()
# Go to the Google home page
driver.get('https://www.google.com')
# Access requests via the `requests` attribute
for request in driver.requests:
if request.response:
print(
request.url,
request.response.status_code,
request.response.headers['Content-Type']
)
위 코드는 Selenium-wire에서 제공하는 예제이며 기존 크롤링 코드에서 import하는 부분만 from seleniumwire import webdriver로 변경 후, driver.requests에서 받아오실 수 있습니다.