2012-09-12 57 views
9

我試圖自動化管理任務,到目前爲止,我已經讓硒點擊一個元素來顯示下拉菜單。點擊與Selenium Webdriver下拉元素菜單

enter image description here

當談到點擊這些菜單元素我有一個錯誤,指出該元素必須顯示的一個時間。

代碼:

driver = webdriver.Chrome() 
driver.implicitly_wait(10) 
driver.get(url) 
doc = driver.find_element_by_css_selector('td.ms-vb-title > table') 
try: 
    doc.click() 
    time.sleep(4) 
    menu = driver.find_element_by_xpath('//menu/span[5]') 
    time.sleep(4) 
    print dir(menu) 
    menu.click() 
except: 
    traceback.print_exc() 
    driver.quit() 

錯誤:

Traceback (most recent call last): 
    File "aprobar_docs.py", line 22, in main 
    menu.click() 
    File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", 
line 52, in click 
    self._execute(Command.CLICK_ELEMENT) 
    File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webelement.py", 
line 205, in _execute 
    return self._parent.execute(command, params) 
    File "C:\Python27\lib\site-packages\selenium\webdriver\remote\webdriver.py", l 
ine 156, in execute 
    self.error_handler.check_response(response) 
    File "C:\Python27\lib\site-packages\selenium\webdriver\remote\errorhandler.py" 
, line 147, in check_response 
    raise exception_class(message, screen, stacktrace) 
ElementNotVisibleException: Message: u'Element must be displayed to click' 

正如你所看到的代碼等待了很多獲得元素加載。我也嘗試將元素的is_displayed屬性設置爲True,但都沒有工作。

注:這不是顯示的元素是在XPath的搜索的一個,它是存在,因爲我已經與DIR(菜單)登錄它

編輯:

menu變量不菜單本身是菜單元素的跨度之一,docPerfil html元素獲得點擊以顯示下拉菜單。

編輯2:

檢查在Chrome工具DOM,當你點擊一個doc一個新的菜單大幹快上樹創建的,我不知道這是否是因爲Ajax調用或香草JS的,我不認爲這是如此重要的創建。我無法從頁面中檢索它,並從中創建一個python對象,它至少在代碼中不顯示。

最後編輯:

我結束了在執行一些JavaScript,使其工作。顯然,當Selenium發現菜單項時,觸發菜單下拉菜單的第一個元素會失去焦點,並且它會使菜單再次不可見,如果您沒有選擇菜單項並等待一段時間仍然顯示菜單下拉列表,則可以嘗試從菜單中選擇一個元素,菜單消失。

+1

你爲什麼睡在'menu'元素查找的兩面?如果元素在檢索頁面元素時不可見,無論您等待多久,webdriver都將無法點擊它。 –

+0

@ sr2222當您調用driver.get()時,會檢索頁面,當您執行doc.click()時,下拉列表將顯示在屏幕上並顯示在dom樹上,我只是消除了未加載下拉菜單的可能性與代碼執行一樣快。菜單元素存在並可見,至少對人類來說,我可以保證。 – loki

+0

嘗試在單擊並等待菜單顯示後再次提取'doc',並比較前後對象的id屬性。我懷疑selenium服務器實際上是在第二次元素提取時引用緩存的webelement對象(因爲您的點擊操作不會觸發頁面加載事件,頁面對象不會過時)。 –

回答

8

你爲什麼不選擇這樣的

el = driver.find_element_by_id('id_of_select') 
for option in el.find_elements_by_tag_name('option'): 
    if option.text == 'The Options I Am Looking For': 
     option.click() # select() in earlier versions of webdriver 

一個選項,如果你的點擊是不觸發Ajax調用來填充你的列表,你實際上並不需要執行點擊。

+0

@Nllesh Sharma我使用這種方法,但我得到的錯誤是web元素對象不可迭代。如何在for循環中迭代它,如果它不可迭代 – abhi

+0

@abhi您確定使用find_elementSSSSS_by_tag_name()嗎? (只是爲了確保你看到了這個嘿嘿) –

0

您需要找到目標的鏈接。你不要真的點擊元素,你點擊鏈接...(或者說,你點擊元素與鏈接裏面)。話雖如此,點擊鏈接的最有效的方法是隔離鏈接元素。

frame = driver.find_element_by_id('this_is_your_frame_name') 
links = frame.find_elements_by_xpath('.//a') 
links[1].click() 

或替代,

for link in links: 
    if link.text() == "Administratar Permisos": 
     link.click() 
相關問題