首页 > 解决方案 > 如何使用 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 是动态创建的,类名也不唯一,如何给这个输入框赋值。

标签: pythonselenium-webdriveruser-input

解决方案


查找以.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')

推荐阅读