【问题标题】:Why can't I select menus through selenium?为什么我不能通过 selenium 选择菜单?
【发布时间】:2021-05-20 07:03:34
【问题描述】:
<div class="fancy-select" data-file=""><label>Choose a file</label>
<select>
  <option value="admin_20210519182831.log">SaveFiles\Logs\admin_20210519182831.log</option>
  <option value="admin_20210519183038.log">SaveFiles\Logs\admin_20210519183038.log</option>
  <option value="chat_20210519182831.log">SaveFiles\Logs\chat_20210519182831.log</option>
  <option value="chat_20210519183038.log">SaveFiles\Logs\chat_20210519183038.log</option>
</select>

我的代码

get_div = Select(driver.find_element_by_class_name('fancy-select'))
get_div.select_by_value("chat_20210519183038.log")

错误

Traceback (most recent call last):
  File "C:\Users\Up\Desktop\New folder\test02.py", line 36, in <module>
    get_div = Select(driver.find_element_by_class_name('fancy-select'))
  File "C:\Users\Up\AppData\Roaming\Python\Python39\site-packages\selenium\webdriver\support\select.py", line 37, in __init__
    raise UnexpectedTagNameException(
selenium.common.exceptions.UnexpectedTagNameException: Message: Select only works on <select> elements, not on <div>

第 36 行

get_div = Select(driver.find_element_by_class_name('fancy-select'))

我已经被这个错误困扰了很长时间,试图弄清楚并尝试修复它,但它没有通过。请帮助知道帮助的人。

【问题讨论】:

    标签: python python-3.x selenium selenium-webdriver


    【解决方案1】:

    看到你得到的错误UnexpectedTagNameException: Message: Select only works on &lt;select&gt; elements, not on &lt;div&gt;你需要做的就是传递选择标签定位器。

    您在 Select 类中定位 div。从 selenium 中选择类只了解选择标签。所以改变你的定位器可能对你有用。

    XPATH:

    //lable[text()='Choose a file']/following-sibling::select
    

    代码:

    get_div = Select(driver.find_element_by_xpath("//lable[text()='Choose a file']/following-sibling::select"))
    get_div.select_by_value("chat_20210519183038.log")
    

    【讨论】:

    • 为什么不 "//div[@class='fancy-select']/select" ?按类名选择应该比按元素文本好。
    • @Prophet :这里的文本是Choose a file,所以它会改变的机会非常小。你的定位器也很好,但我认为可能会有不止一个类名fancy-select
    【解决方案2】:

    你可以尝试给选择标签一个id fancy-sel:

    select = Select(driver.find_element_by_id('fancy-sel'))
    
    # select by visible text
    select.select_by_visible_text('SaveFiles\Logs\chat_20210519183038.log')
    
    # select by value 
    select.select_by_value('chat_20210519183038.log')
    

    【讨论】:

    • 不要提及LOLweird遵循here的指导方针
    猜你喜欢
    • 1970-01-01
    • 2015-05-15
    • 1970-01-01
    • 2020-11-10
    • 2017-06-27
    • 2015-12-15
    • 2016-08-18
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多