Dev/Python

웹스크래핑 - Web Scraping

healthyryu 2022. 10. 2. 23:59

웹 스크래핑에서 사용할 라이브러리

 

- Selenium

    - webdriver

    - ChromDriveManager

    - By

    - Service

    - EC

- json

 

Selenium 은 웹 브라우저를 원하는 대로 제어하기 위한 라이브러리이다. 그리고 WebDriver 는 Selenium 을 사용하기 위해서 필요하다.

 

1. Selenium 을 사용하기 위한 드라이버 설정 작업

def set_driver():
    chrome_options = webdriver.ChromeOptions()
    // 크롬 브라우저를 열지 않고 동작 하도록
    chrome_options.headless = True
    driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=chrome_options)
    return driver

 

2. 크롬에서 해당 URL 열기

url = "http://www.naver.com"

browser = set_driver()
browser.get(url)

 

3. 해당 페이지에서 특정 엘리먼트 찾기 - 버튼 찾기

// ID 값 search_btn 찾기
browser.find_element(By.ID, "search_btn")

 

4. 데이터를 json 형태로 변환해서 저장하는 작업

with open("outfile.json", "w", encoding="utf-8") as f:
    f.write(json.dumps(out, ensure_ascii=False, indent=4))

 

5. 분리 및 공백 제거 작업

// class_name 클래스의 텍스트 추출
info = item.find_element(By.CLASS_NAME, "class_name").text
// info 라는 텍스트에 "|" 구분해서 나눠서 리스트에 담고 -> 리스트의 첫번째 문자의 공백을 제거
text = info.split("|")[0].strip()

 

6. XPATH 로 Element 찾기

// div 태그 안의 attribute 가 data-clk-prefix 이고 값이 sch 요소
elem.find_element(By.XPATH, "//div[contains(@data-clk-prefix, 'sch')]")

반응형