【问题标题】:Python Selenium - Multiple choice field (django-select2) - Cannot get a value by XPATHPython Selenium - 多项选择字段(django-select2) - 无法通过 XPATH 获取值
【发布时间】:2015-12-02 20:23:10
【问题描述】:

我正在尝试从多项选择字段(类别)中获取随机值以在 Python Selenium 中进行测试:

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>

并选择一个随机值。

使用我的代码它不起作用,它甚至不打印元素的数量:

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

这是来自 Chrome 控制台的代码:

【问题讨论】:

    标签: python django forms xpath selenium-webdriver


    【解决方案1】:

    通过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()
    

    【讨论】:

    • 我得到:AttributeError: Select instance has no attribute 'click'
    • 嗯...下一个问题是:消息:元素不可见
    • 我将我的 ID 更改为“s2id_autogen1”并得到: UnexpectedTagNameException: Message: Select only works on
    猜你喜欢
    • 1970-01-01
    • 2021-09-29
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    相关资源
    最近更新 更多