1. 라이브러리 선언 및 드라이버 설정

# 라이브러리 선언
from selenium import webdriver

# 드라이버 위치 설정
driver_loc = "d:/chromedriver/chromedriver.exe"

# 드라이버 옵션 설정
options = webdriver.ChromeOptions()
options.add_argument("window-size=1920x1080")

# 헤드리스 설정 시 리눅스 같이 웹화면 없는경우에도 웹페이지 실행가능함
# options.add_argument('headless’)
# options.add_argument("disable-gpu")
# 웹 드라이버 정의
driver = webdriver.Chrome(driver_loc, options=options)
# 웹페이지 파싱 될때까지 최대 3초 기다림
driver.implicitly_wait(3)

2. 웹 페이지 이동

# URL 정의
baseUrl = "https://sparkkorea.com"
# URL 이동
driver.get(baseUrl)
# 현재 URL 정보 
driver.current_url

3. 액션 대상 요소 탐색

# 웹 페이지에서 원하는 요소 선택 (우클릭 후 검사) 이후 소스코드 영역에서 우클릭 후 COPY X PATH (* 클래스 속성으로 등으로도 접근가능)

serchPath = '//*[@id="menu-item-382"]/a'

4. 액션 적용하기 (키 입력)

from selenium.webdriver.common.keys import Keys

# URL 정의
googleUrl = 'https://www.google.co.kr'
# URL 이동
driver.get(googleUrl)
# 요소 탐색
searchPath = '//*[@id="tsf"]/div[2]/div[1]/div[1]/div/div[2]/input'
driver.find_element_by_xpath(searchPath).send_keys("selenium wiki")
driver.find_element_by_xpath(searchPath).send_keys(Keys.ENTER)

4. 액션 적용하기 (클릭)

# URL 정의
sparkUrl = 'https://sparkkorea.com'

# URL 이동
driver.implicitly_wait(3)
driver.get(sparkUrl)

quizBtnXpath = '//*[@id="menu-item-382"]/a'
driver.find_element_by_xpath(quizBtnXpath).click()
time.sleep(3)    # 3초간 기다림

5. 웹 페이지 소스 가져오기

# 페이지 소스 가져오기 전 대기 (절대시간 1초)
import time
time.sleep(1)

# 현재 페이지 소스 가져오기
html = driver.page_source

import bs4
# BeautifulSoup로 페이지 소스 파싱
bs = bs4.BeautifulSoup(html,"html.parser")

6. 페이지 스크랩 및 저장하기

# 퀴즈 정보 스크랩
spQuizTag = bs.find(name="div", attrs={"id":"id_spark_quiz"})

spQuizTagLinks = spQuizTag.findAll("a")

titleList = []
linkList = []

for i in range(0, len(spQuizTagLinks)):
    titleInfo = spQuizTagLinks[0].text
    linkInfo = spQuizTagLinks[0].attrs["href"]
    titleList.append(titleInfo)
    linkList.append(linkInfo)
    
# 데이터프레임 변환
import pandas as pd
finalResult = pd.DataFrame( zip(titleList, linkList) , columns = ["제목", "링크"])

# csv 파일로 저장
finalResult.to_csv("./link_scraping_result.csv",encoding="ms949", index=False)

 

 

액션 고급

1. 쿠팡 접속 메뉴 연속 선택

from selenium.webdriver.common.action_chains import ActionChains
coupangUrl = 'http://www.coupang.com'
driver.get(coupangUrl)

2. 쿠팡 접속 메뉴 연속 선택

# 카테고리 메뉴 (카테고리 -> 식품 -> 축산/계란 -> 게략/알류/가공란)
mainMenu = '//*[@id="header"]/div/a'
subMenu = '//*[@id="gnbAnalytics"]/ul[1]/li[4]/a'
subMenu2 = '//*[@id="gnbAnalytics"]/ul[1]/li[4]/div/div/ul/li[6]/a'
targetMenu = '//*[@id="gnbAnalytics"]/ul[1]/li[4]/div/div/ul/li[6]/div/ul/li[6]/a'
main = driver.find_element_by_xpath(mainMenu)
sub = driver.find_element_by_xpath(subMenu)
sub2 = driver.find_element_by_xpath(subMenu2)
target = driver.find_element_by_xpath(targetMenu)
ActionChains(driver).move_to_element(main).move_to_element(sub).move_to_element(sub2).click(target).perform()

액션 적용 시 기다렸다가 클릭하기

# URL 정의
baseUrl = "https://sparkkorea.com"
# URL 이동
driver.get(baseUrl)

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC


# driver.find_element_by_xpath(mainTitle).is_displayed()

quizMenu = '//*[@id="menu-item-382"]/a'
element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.XPATH, quizMenu)))
driver.find_element_by_xpath(quizMenu).click()
# mainMenu = '//*[@id="site-navigation"]/button'
# subMenu = '//*[@id="menu-item-382"]/a'

# try:
#     # 메인 메뉴가 있을때 메인메뉴 클릭하고 퀴즈 메뉴 선택
#     driver.find_element_by_xpath(mainMenu).click()
#     driver.find_element_by_xpath(subMenu).click()
# except Exception as e:
#     # 메인 메뉴 없는 경우 퀴즈 메뉴 바로 선택
#     print("menu not founded")
#     driver.find_element_by_xpath(subMenu).click()

 

 

 

from selenium import webdriver

driver.get(url) : url로 이동
driver.page_source : 현재 페이지의 HTML 태그를 저장한다. requests.get(url).text와 같다.

driver.find_element_by_xpath(xPath).click() : 클릭.
driver.find_element_by_xpath(xPath).send_keys('ABC') : 'ABC'를 입력.
driver.find_element_by_xpath(xPath).send_keys(Keys.ENTER) : return 입력. (반드시 ENTER를 대문자로 입력해야한다.)

Selenium Keys

더보기

i.e. send_keys(Keys.ENTER) 는 send_keys("\ue007")과 같다.

KEYS =
See Also:
Element#send_keys
http://www.google.com.au/search?&q=unicode+pua&btnK=Search
{
  null: "\ue000",
  cancel: "\ue001",
  help: "\ue002",
  backspace: "\ue003",
  tab: "\ue004",
  clear: "\ue005",
  return: "\ue006",
  enter: "\ue007",
  shift: "\ue008",
  left_shift: "\ue008",
  control: "\ue009",
  left_control: "\ue009",
  alt: "\ue00A",
  left_alt: "\ue00A",
  pause: "\ue00B",
  escape: "\ue00C",
  space: "\ue00D",
  page_up: "\ue00E",
  page_down: "\ue00F",
  end: "\ue010",
  home: "\ue011",
  left: "\ue012",
  arrow_left: "\ue012",
  up: "\ue013",
  arrow_up: "\ue013",
  right: "\ue014",
  arrow_right: "\ue014",
  down: "\ue015",
  arrow_down: "\ue015",
  insert: "\ue016",
  delete: "\ue017",
  semicolon: "\ue018",
  equals: "\ue019",
  numpad0: "\ue01A",
  numpad1: "\ue01B",
  numpad2: "\ue01C",
  numpad3: "\ue01D",
  numpad4: "\ue01E",
  numpad5: "\ue01F",
  numpad6: "\ue020",
  numpad7: "\ue021",
  numpad8: "\ue022",
  numpad9: "\ue023",
  multiply: "\ue024",
  add: "\ue025",
  separator: "\ue026",
  subtract: "\ue027",
  decimal: "\ue028",
  divide: "\ue029",
  f1: "\ue031",
  f2: "\ue032",
  f3: "\ue033",
  f4: "\ue034",
  f5: "\ue035",
  f6: "\ue036",
  f7: "\ue037",
  f8: "\ue038",
  f9: "\ue039",
  f10: "\ue03A",
  f11: "\ue03B",
  f12: "\ue03C",
  meta: "\ue03D",
  command: "\ue03D", # alias
  left_meta: "\ue03D", # alias
  right_shift: "\ue050",
  right_control: "\ue051",
  right_alt: "\ue052",
  right_meta: "\ue053",
  numpad_page_up: "\ue054",
  numpad_page_down: "\ue055",
  numpad_end: "\ue056",
  numpad_home: "\ue057",
  numpad_left: "\ue058",
  numpad_up: "\ue059",
  numpad_right: "\ue05A",
  numpad_down: "\ue05B",
  numpad_insert: "\ue05C",
  numpad_delete: "\ue05D"
}.freeze

action1 = driver.find_element_by_xpath(xPath1)
action2 = driver.find_element_by_xpath(xPath2)
ActionCahins.move_to_element(action1).click(action2).perform() : 마지막 perform()에 의해 순차적으로 실행.

# example

from selenium.webdriver.common.action_chains import ActionChains

coupangUrl = 'http://www.coupang.com'
driver.get(coupangUrl)

mainMenu = '//*[@id="header"]/div/a'
subMenu = '//*[@id="gnbAnalytics"]/ul[1]/li[4]/a'
subMenu2 = '//*[@id="gnbAnalytics"]/ul[1]/li[4]/div/div/ul/li[6]/a'
targetMenu = '//*[@id="gnbAnalytics"]/ul[1]/li[4]/div/div/ul/li[6]/div/ul/li[6]/a'
main = driver.find_element_by_xpath(mainMenu)
sub = driver.find_element_by_xpath(subMenu)
sub2 = driver.find_element_by_xpath(subMenu2)
target = driver.find_element_by_xpath(targetMenu)
ActionChains(driver).move_to_element(main).move_to_element(sub).move_to_element(sub2).click(target).perform()

time.sleep(3) : import time 필요.
driver.implicitly_wait(3) : 셀레니움 드라이버의 함수

driver.close() : 종료.

+ Recent posts