2013-05-29 44 views
11

使用Python版本的Selenium,是否可以點擊DOM中的某個元素並指定想要點擊它的座標? Java版本的方法clickAt,實際上它正是我正在查找的內容,但無法在Python中找到等價物。硒 - 在特定位置點擊

回答

1

我沒有親自使用這種方法,而是通過selenium.py源代碼找我發現下面的方法,看上去就像他們會做你想要的東西 - 它們看上去包裝clickAt

def click_at(self,locator,coordString): 
    """ 
    Clicks on a link, button, checkbox or radio button. If the click action 
    causes a new page to load (like a link usually does), call 
    waitForPageToLoad. 

    'locator' is an element locator 
    'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse  event relative to the element returned by the locator. 
    """ 
    self.do_command("clickAt", [locator,coordString,]) 


def double_click_at(self,locator,coordString): 
    """ 
    Doubleclicks on a link, button, checkbox or radio button. If the action 
    causes a new page to load (like a link usually does), call 
    waitForPageToLoad. 

    'locator' is an element locator 
    'coordString' is specifies the x,y position (i.e. - 10,20) of the mouse  event relative to the element returned by the locator. 
    """ 
    self.do_command("doubleClickAt", [locator,coordString,]) 

它們出現在硒對象中,這裏是它們的online API documentation

+0

太棒了!他們屬於哪個班級? – davids

+0

他們在硒對象。實際上我剛剛在網上找到了他們的API文檔 - 更新了答案。 – Ewan

+0

還有一個問題。你怎麼實際使用它?我習慣使用webdrivers對象,但從未使用過這個 – davids

4

您感到困惑的原因是clickAt是一箇舊的v1(Selenium RC)方法。

WebDriver有一個略有不同的概念,'Actions'

具體而言,Python綁定的'Actions'生成器生效here

clickAt命令的想法是點擊某個位置相對於到一個特定的元素。

在WebDriver中使用'Actions'構建器可以實現同樣的效果。

希望這updated documentation可以幫助。

22

這應該做到這一點!即你需要使用webdriver的動作鏈。一旦你有一個實例,你只需註冊一堆行動,然後致電perform()執行它們。

from selenium import webdriver 
driver = webdriver.Firefox() 
driver.get("http://www.google.com") 
el=driver.find_elements_by_xpath("//button[contains(string(), 'Lucky')]")[0] 

action = webdriver.common.action_chains.ActionChains(driver) 
action.move_to_element_with_offset(el, 5, 5) 
action.click() 
action.perform() 

這將從按鈕的左上角右移動鼠標5個像素下來,5個像素我覺得很幸運。那麼它會click()

請注意,您必須使用perform()。否則什麼都不會發生。