{%hackmd @rpyapp/theme %} # Python Selenium Notes ###### tags: `Python` `Selenium` `Notes` [TOC] ## 基本用法 > 通常都會搭配等待秒數使用 ```python= import time from selenium import webdriver driver = webdriver.Chrome() driver.get('http://eip.ym.edu.tw/EIP/login.aspx') driver.find_element_by_xpath('//*[@id="tb_eipea_account_emp_account"]').send_keys('輸入帳號') driver.find_element_by_xpath('//*[@id="tb_eipea_account_emp_account"]').clear() driver.find_element_by_xpath('//*[@id="btn_login"]').click() time.sleep(5) ``` > 取得所有使用 classA 的 elements ```python= contents = driver.find_elements_by_class_name('classA') for element in contents: print(element.text) ``` > 某個 element 中的 source 資訊 ```python= element.get_attribute('innerHTML') ``` ## 特殊用法 > 有時找不到 element 是因為 frame 的關係,切換進去就可以找到 ```python= driver.switch_to.frame('subap_frame') ``` > 或是需要退到上層 frame ```python= driver.switch_to.parent_frame() ``` > 處理 alert 視窗 ```python= def acecptAlert(): try: Alert(driver).accept() except: print('no alert') time.sleep(5) ``` > 表格中的 row 2 column 3 ```python= driver.find_element_by_xpath('*/table/tbody/tr[2]/td[3]') ``` > 下拉選單選擇某個選項 ```python= driver.find_element_by_xpath('*/select/option[text()="選項A"]').click() ``` > 默認等待時間,在設定時間結束之前有接收到東西的話就會繼續 ```python= driver.implicitly_wait(30) ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up