2015-12-02 99 views
1

我想從多選場(類別)的隨機值,使Python中硒測試得到的值:Python的硒 - 多選場(Django的選擇2) - 無法通過XPATH

tag = driver.find_element_by_xpath("//*[@id='s2id_autogen2']") 

如果我要發送只是一個字符串,該工程如:

tag.send_keys("some_text") 

但我想獲得那些期權值(網頁源代碼):

<div class="form-select-container" > 
     <select multiple="multiple" class="django-select2" data-allow-clear="false" data-minimum-input-length="0" id="id_categories" name="categories"> 
     <option value="1">String1</option> 
     <option value="2">String2</option> 
     <option value="3">String3</option> 
</select> 
</div> 

然後選擇一個隨機值。從Chrome的控制檯

for i in tag: 
    print len(i) 
    #print (random.choice(i))(Keys.ENTER) 

而這種代碼::

我的代碼它不工作,它甚至不打印元件的數量 Chrome Code

回答

0

通過定位選擇元素id,實例化Select object,得到.options和隨機挑選使用random.choice()之一:

import random 

from selenium.webdriver.support.select import Select 

# get a random option 
select_elm = driver.find_element_by_id("id_categories") 
select = Select(select_elm) 
random_option = random.choice(select.options) 

# select the random option 
select_elm.click() 
random_option.click() 
+0

我得到:AttributeError:選擇實例沒有屬性'點擊' –

+0

@MaciejJanuszewski肯定,更新。 – alecxe

+0

嗯......接下來的問題是:消息:元素不可見 –