1. 程式人生 > >由官方文件看selenium(2)

由官方文件看selenium(2)

1.ActionChains類滑鼠操作常用方法:


引入ActionChains類:

<span style="font-size:18px;">from selenium.webdriver import ActionChains
</span>

context_click()    右擊

<span style="font-size:18px;">RightClick = driver.find_element_by_id("id")
ActionChains(driver).context_click(RightClick).perform()</span>

double_click()    雙擊
<span style="font-size:18px;">DoubleClick = driver.find_element_by_name("name")
ActionChains(driver).double_click(DoubleClick).perform()</span>

drag_and_drop(source, target)    滑鼠拖放

source:滑鼠按下的源元素;target:滑鼠釋放的目標元素

<span style="font-size:18px;">element = driver.find_element_by_name("name")
target = driver.find_element_by_name("name")
ActionChains(driver).drag_and_drop(element, target).perform()</span>

move_to_element()    滑鼠懸停在一個元素上
<span style="font-size:18px;">above = driver.find_element_by_xpath("xpath路徑")
ActionChains(driver).move_to_element(above).perform()</span>

click_and_hold()    按下滑鼠左鍵在一個元素上

<span style="font-size:18px;">left = driver.find_element_by_name("name")
ActionChains(driver).click_and_hold(left).perform()</span>

2.在視窗和frame之間切換:


現代的web應用常常會在頁面中巢狀frame或者是視窗,這給我們定位元素帶來一定的困難。如果元素是在一個iframe內的話,直接使用find_element_by_*()系列的方法有時候會找不到想要的元素的。

這個時候需要使用:

<span style="font-size:18px;">driver.switch_to_frame("framename或者id")</span>

來切換到包含該元素的iframe

我們也可以使用.來獲取到下一級的frame,可以指明子frame的索引號:

driver.switch_to_frame("frameName.0.child")
這樣就會切換到name或id=frameName的第一個子frame中name=child的frame中

當要從該iframe中出去時要呼叫driver.switch_to_default_content(),返回到主content,也就是主介面中

當要切換多視窗的時候:使用

<span style="font-size:18px;">driver.switch_to_window("windowName")</span>

如果不知道windowName,可以看一下開啟該視窗的JS或者連線:

例如:

<a href="somewhere.html" target="windowName">Click here to open a new window</a>


當然你也可以傳遞一個視窗的控制代碼到switch_to_window()方法:

可以通過這種方法迭代地開啟所有視窗:

for handle in driver.window_handles:
    driver.switch_to_window(handle)

3.處理彈出視窗:

當你觸發一個導致彈出視窗的動作時,可以用switch_to_alert()方法切換到彈出視窗

alert = driver.switch_to_alert()

這樣會返回當前彈出框的物件,使用這個物件可以對彈出框進行操作。

4.處理Cookies:

要處理Cookie首先要到該域下:

如下:

# Go to the correct domain
driver.get("http://www.example.com")

# Now set the cookie. This one's valid for the entire domain
cookie = {‘name’ : ‘foo’, ‘value’ : ‘bar’}
driver.add_cookie(cookie)

# And now output all the available cookies for the current URL
driver.get_cookies()