카테고리 없음

[파이썬크롤링] Selenium 심화, 브라우저 제어

Yeni_aa 2022. 6. 29. 22:08
 

 

 

 

 

 

 

 

2.  브라우저 로딩 기다리기

 

로딩을 기다리는 세가지 방법

  • 무조건 기다리기: time_sleep( )
  • 암시적 기다리기: implicitly_wait( ) 최대 n초까지 기다림. 
  • 명시적 기다리기: 기다릴 요소를 명시하여 최대 n초까지 기다리는 것. presence_of_element_located( ) , element_to_be_clickable( )

 

 

#1번
import time

with webdriver.Firefox() as driver:
    driver.get(url)  # (a)
    time.sleep(10)  # (b)

    e = driver.find_element()
    ...

1번 코드는 명시적 기다리기 수행 방법으로, n초간 무조건 기다림을 수행한다.

#2번
with webdriver.Firefox() as driver:
    driver.implicitly_wait(10)

    driver.get(url)

    e = driver.find_element()...

2번 코드는 해당 요소의 로딩이 끝나면 기다리기를 즉시 종료하고 코드를 실행한다. --> 명시적 기다리기 이니까 implicitly_wait()

2번 코드가 한 번만 설정해주면 계속해서 적용된다는 장점이 있다.

 

3. 키보드/마우스 입력하기

from selenium.webdriver.common.keys import Keys

"""
1번
"""
driver.find_element_by_xpath('//*[@id="id"]').send_keys("my_id")

"""
2번
"""
driver.find_element_by_xpath('//*[@id="pw"]').send_keys("my_password" + Keys.ENTER)

"""
3번
"""
driver.find_element_by_xpath('//*[@id="log.login"]').click()

1번 코드는 m, y, _, i, d 를 순차적으로 입력한다.

2번 코드는 패스워드를 순차적으로 입력 후 ENTER 버튼을 클릭

3번 코드는 로그인 버튼을 클릭할 수 있도록 한다.

 

from selenium import webdriver
#실습 
with webdriver.Firefox() as driver:
    driver.get("http://localhost:8080")

    input_id = input()
    input_pw = input()

    # 지시사항 1번과 2번을 작성하세요.
    id_element = driver.find_element_by_id('id') #2장 참고
    id_element.send_keys(input_id) #자동으로 입력되게 끔 
    
    # 지시사항 3번을 작성하세요.
    pw_element = driver.find_element_by_id('pw')
    pw_element.send_keys(input_pw)
    
    # 지시사항 4번을 작성하세요.
    button = driver.find_element_by_id('login') #버튼 요소 찾아오고
    button.click() #클릭 메소드 사용하기 
    
    # 지시사항 5번을 작성하세요.
    message = driver.find_element_by_id('message')
    print(message.text)

4. 액션체인

 

Acction Chains란

기본 입력을 통해서는 각 요소에 key sequence를 입력할 수는 있으나, 더 복잡한 액션을 하기 어렵다.

ActionChains는 이름 뜻 그래도 여러 가지의 action을 chain처럼 엮어 수행한다.

ActionChains을 활용할 경우 다양한 메서드의 조합을 통해 원하는 액션을 구현할 수 있다.

 

<액션체인을 구현하는 두가지 방법>

  • Class Method 로 사용
  • 인스턴스로 만들어 사용

 

액션체인 활용 실습

from selenium import webdriver

with webdriver.Firefox() as driver:
    driver.get("http://localhost:8080")

    input_id = input()
    input_pw = input()

    # 지시사항 1번을 작성하세요.
    id_e = driver.find_element_by_id('id') #해당하는 요소를 찾아와서 변수에 집어 넣기
    pw_e = driver.find_element_by_id('pw')
    login_e = driver.find_element_by_id('login')

    # 지시사항 2번을 작성하세요. 인스턴스로 만들어 놓고 쓰기로 
    chains = webdriver.ActionChains(driver)

    # 지시사항 3번을 작성하세요.
    chains.send_keys_to_element(id_e, input_id) #요소에 input_id를 넣기
    chains.send_keys_to_element(pw_e, input_pw)
    # 지시사항 4번을 작성하세요.
    chains.click(login_e) #로그인 요소를 클릭하세요
    # 지시사항 5번을 작성하세요.
    chains.perform() #이제 액션체인에 모두 넣었으니 perform

    message = driver.find_element_by_id('message')
    print(message.text)