2019년 1월 13일 일요일

[Python] 웹다루기 2


Action Chain의 사용과 XPATH 활용

  • action chain으로 사용하기 어려운 element를 찾아가 동작을 취하기
  • xpath로 tree 찾아가거나 연산 및 함수로 해당 element 찾가아기 ex) rows = form.find_elements_by_xpath('./table/tbody/tr')
  • iframe 사용 driver.switch_to_frame(iframe) driver.switch_to_default_content()
  • current_url : 현재 접속 중인 웹 사이트의 주소
  • windows : 현재 열려있는 창의 리스트
  • 기타 동작들 : click(), context_click(), double_click(), move_by_offset(x, y), send_keys(), perform()
In  [1]:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import time
driver = webdriver.Chrome('./chromedriver')
try:
time.sleep(5)
action = ActionChains(driver)
elem = driver.find_element_by_xpath("//button[contains(@class, 'L3NKy')]")
action.reset_actions()
action.move_to_element(elem)
action.click()
action.perform()
time.sleep(2)
elem = driver.find_element_by_id('email')
elem.send_keys('아이디')
elem = driver.find_element_by_id('pass')
elem.send_keys('비밀번호')
elem = driver.find_element_by_id('loginbutton')
elem.click()
except expression as identifier:
pass
finally:
driver.quit()

Xpath에서 사용할 수 있는 조건은 =, <과 같은 연산자와 contains 등의 함수를 사용 가능

이 함수들의 목록은 https://www.w3schools.com/xml/xsl_functions.asp 에서 확인 가능

XPATH 활용법

./li 현재 태그의 바로 하위에 있는 li 태그
../li 현재 상위에 있는 태그의 하위에 있는 li 태그
//li 문서 전체 중 모든 li 태그
//li//li 문서 전체 중 모든 li 태그의 하위에 있는 모든 li 태그
//li[@id='myid'] 문서 전체 중 id 속성이 'myid'인 li 태그
//*[@id='myid'] 문서 전체 중 id 속성이 'myid'인 모든 태그
//input[@class!='myclass'] 문서 전체중 class 속성에 'myclass'가 없는 모든 태그
//a[text()='2'] 문서 전체 중 태그 내용이 '2'인 a 태그
//a[contatins(text(), '다음')] 문서 전체 중 태그 내용에 '다음'이 포함되는 a 태그
//a[contains(@id, 'this')] 문서 전체 중 id 속성에 'this'가 포함된 a 태그
//a[starts-with(@id, 'this')] 문서 전체 중 id 속성이 'this'로 시작되는 a 태그

페이지 로딩까지 기다리기

from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
(중략)
wait = webDriverWiat(driver, 60)
cond = EC.element_to_be_clickable((By.LINK_TEXT, '로그인')) btn = wait.unitl(cond) btn.click()
(후략)

parameters

  • By.ID, By.XPATH, By.LINK_TEXT, By.PARTIAL_LINK_TEXT, By.NAME, By.TAG_NAME, By.CLASS_NAME

conditions

  • title_is
  • title_contais
  • url_contains
  • visibility_of_element_located
  • text_to_be_present_in_element
  • element_to_be_clickable

알림창 handling

(중략)
alert = Alert(driver) alert.accpet() # 확인버튼 alert.dismiss() # 취소버튼
(후략)

새로운 창 다루기

(중략)
wins = driver.window_handles driver.switch_to_window(wins[1])
(후략)


Background로 띄우기 


opts = webdriver.ChromeOptions()
opts.add_argument('headless')                        # 백그라운드 실행
opts.add_argument('window-size=1920,1080')    # 작은 창 크기로 백그라운드에서 실행되어 화면구성이 달라지는 것을 대비

driver = webdriver.Chrome('./chromedriver', chrome_options=opts)

댓글 없음:

댓글 쓰기

200926.가오리코스 라이딩

9/26 골절인지 아닌지 확인 안됨. 이후 미세골절여부 확인 핸드폰을 드는 것도 어려움 9/29 x ray 다시 찍지 않고 이후 재 방문 요청 ...