Selenium + Python requests + ChromeDriver #2

지난 포스팅에서는 Chrome Driver 세팅까지 끝냈다.(너무 오래 지났네...ㅠ.ㅠ)

이렇게 셋팅이 되고 나면 Chrome Driver 를 통해 웹페이지를 호출하면

Ajax 나 JQuery 로 된 페이지의 모든 내용을 다 가져올 수 있다

먼저 앞에서 설명한 내용을 다시 보여드리면

from selenium import webdriver
from selenium.webdriver.chrome.options import Options


options = Options()
options.headless = Truedriver = webdriver.Chrome(CHROMEDRIVER_PATH, chrome_options=options)

위와 같이 셋팅된 driver 객체를 url 과 data(Dictionary 형태) 와 함께 requests 에 던져주면 된다.

def httpRequestWithDriver(driver, url, data, method='POST'):
    try:
        req = request(driver)
        if method == 'POST':
            r = req.post(url, data)
            return r.content
        else:
            r = req.get(url, params=data)
            return r.content
    except Exception as e:
        print(e)

여기서 잠깐!!

request 는 뭔가 생소하다

def request(driver):
    s = requests.Session()
    # cookies = driver.get_cookies()
    # for cookie in cookies:
    #     s.cookies.set(cookie['name'], cookie['value'])
    return s

쿠키까지 셋팅하고 싶다고 하면 주석처리된 부분을 풀고 실행하면 될 듯.

끝!!

댓글 없음:

댓글 쓰기

Latest Contents

pytorch installation with GeForce RTX 3050 Ti

 1. Install CUDA toolkit 11.8     ※ WARNING : Please except for "Nsight VSE" to avoid Installation fail.      2. Download cuDNN ( ...

Most viewed