2012-11-12 139 views
1

我使用的是selenium-webdriver,我正在尋找一些非常簡單的東西,但我沒有在文檔中找到它。selenium-webdriver點擊第一個鏈接

這是我的代碼的一部分:

browser = Selenium::WebDriver.for :firefox, :profile => profile 
browser.navigate.to 'an_url' 
# I find ancestor element 
browser.find_element(:id, "displaylinks").find_element(:id, "link0").find_element(:class, "link-center") 
# but I want to click the first link child of this last element 

任何想法?

回答

3

有一對夫婦,你可以使用不同的選擇的:

ancestor_element = browser.find_element(:id, "displaylinks").find_element(:id, "link0").find_element(:class, "link-center") 

#Using tag_name 
ancestor_element.find_element(:tag_name, 'a').click 

#Using css-selector 
ancestor_element.find_element(:css, 'a').click 

#Using xpath-selector (direct child) 
ancestor_element.find_element(:xpath, './a').click 

#Using xpath-selector (anywhere in ancestor)child) 
ancestor_element.find_element(:xpath, './/a').click 
+0

能否請您解釋一下'/了'和'.//了')?用我無法理解的代碼。 – CodeLover

+1

@CodeLover,那些是xpath選擇器。第一個說找到ancestor_element的直接孩子的第一個'a'元素(即鏈接)。第二個說在ancestor_element的任何地方找到鏈接。所以如果你有'

',第一個沒有找到鏈接,而第二個會。有關更多詳細信息,您可能需要閱讀xpath選擇器。 –

+0

'+ 1'給你,非常感謝!如果你想要的話,任何'xpath'上的好材料都可以引用我。 – CodeLover