1. 程式人生 > 實用技巧 >常用元素操作api之呼叫javascript操作(九)

常用元素操作api之呼叫javascript操作(九)

from selenium import webdriver
import time
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.by import By
from slenium_jichu01 import tools
# 呼叫javascript
driver = webdriver.Chrome()
driver.get('https://baidu.com')
driver.implicitly_wait(30)
#演示1,
driver.execute_script('alert("我愛學習,學習愛我")')

time.sleep(2)
driver.switch_to.alert.accept()
#演示2,輸入框高亮顯示
wl = driver.find_element_by_name('wd')
# tools.highlight_element(driver,wl)
# driver.execute_script("arguments[0].style.border='5px solid red'",wl)#加邊框
#演示3,獲取元素屬性
# js= "var user_input = document.getElementById('su').getAttribute('id')"
js_get_name = "return document.getElementById('kw').getAttribute('name')"

js_get_class = "return document.getElementById('kw').getAttribute('class')"
print(driver.execute_script(js_get_name))
print(driver.execute_script(js_get_class))

# 演示4:滾動條的處理
wl=driver.find_element_by_name('wd').send_keys('測試開發')
driver.find_element_by_id('su').click()
time.sleep(2)
# driver.execute_script("document.body.scrollTop=200;")

# js="window.scrollBy(0,300)"
# driver.execute_script(js)
# time.sleep(2)
# js="window.scrollBy(0,400)"
# driver.execute_script(js)
# time.sleep(2)
# js="window.scrollBy(0,200)"
# driver.execute_script(js)
# time.sleep(2)
# js="window.scrollBy(0,-200)"
# driver.execute_script(js)
# time.sleep(2)
# js="window.scrollBy(0,-400)"
# driver.execute_script(js)
# time.sleep(2)
# js="window.scrollBy(0,-300)"
# driver.execute_script(js)
# time.sleep(2)

#封裝一個滾動的方法
def scroll(driver,height):
js = "window.scrollBy(0,"+str(height)+")"
driver.execute_script(js)
time.sleep(2)

scroll(driver,100)
scroll(driver,200)
scroll(driver,500)
scroll(driver,-100)
scroll(driver,-200)
scroll(driver,-500)
#直接滾到底部
scroll(driver,2000)
scroll(driver,-2000)