python - 如何使用 selenium python 为动态输入框赋值
问题描述
我需要将一个值传递给具有动态 id 的动态输入框。我的代码是:
<table id="combobox-1281-triggerWrap" class="x-form-trigger-wrap" cellpadding="0" cellspacing="0" style="width: 100%; table-layout: fixed;">
<tbody><tr>
<td id="combobox-1281-inputCell" class="x-form-trigger-input-cell" style="width: 100%;">
<input id="combobox-1281-inputEl" type="text" role="combobox" class="x-form-field x-form-text x-form-focus x-field-form-focus x-field-default-form-focus" autocomplete="off" name="combobox-1281-inputEl" style="width: 100%;">
<div class="x-hide-display x-form-data-hidden" role="presentation" id="ext-gen1728"></div></td>
<td role="presentation" id="combobox-1281-sideErrorCell" width="22" style="display: none;">
<div role="presentation" id="combobox-1281-errorEl" class="x-form-invalid-icon x-form-invalid-icon-focus" style="display:none">
</div></td>
<td role="presentation" valign="top" class=" x-trigger-cell x-unselectable" style="width:28px;" id="ext-gen1727">
<div class="x-trigger-index-0 x-form-trigger x-form-arrow-trigger x-form-trigger-first rp-icon-expanded" role="presentation" id="ext-gen1726"></div>
</td></tr>
</tbody></table>
这里 "combobox-1281-inputEl" =>1281 是动态创建的,类名也不唯一,如何给这个输入框赋值。
解决方案
查找以.id
开头combobox-
和结尾的部分属性-inputEl
。你可以从父母那里得到<td>
driver.find_element_by_css_selector('[id^="combobox-"][id$="-inputCell"] > [id^="combobox-"][id$="-inputEl"]')
您还可以提取动态部分并使用它来定位其他元素
table = driver.find_element_by_css_selector('[id^="combobox-"][id$="-inputCell"]')
number = table.get_attribute('id').split('-')[1]
driver.find_element_by_id(f'combobox-{number}-inputEl')
推荐阅读
- intellij-idea - IntelliJ 代码完成弹出窗口中 %(百分比符号)的相似性
- algorithm - 如何通过反转子序列对排列进行排序(取自 Skiena 3rd ed。)
- cmake - 具有不同参数的 Cmake 链接库
- javascript - 如何通过在每个值后添加 & 来从对象形成查询 url?
- django - 如何在 VsCode 上访问 Django 源代码?
- kubernetes - 路由特定 IP 和端口的 kubernetes pod 传出流量
- shell - 在 github 中创建的标签的 jenkins 构建的链接 url
- openapi - 使用 @Context 注入 HttpServletRequest 会导致 openapi 向 swagger 添加额外的类
- sql-server - 将 SQL Server 数据库迁移到 Azure SQL 数据库,保留行版本/时间戳
- javascript - 当开关切换到 ON 和 OFF 时需要鼓机工作