Python WEBDRIVER我无法从列表框中选择元素并提交答案

2024-10-03 09:07:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从列表框中选择一个元素,然后提交我的答案,这样我的浏览器就会打开一个包含我选择的元素的新页面。我可以选择参数,但当我按下“搜索”按钮时,它不考虑我的选择。以下是列表框的html:

<select size="10" name="lbSources" id="lbSources" class="form" onkeypress="return OnKeyPressEnterSubmit('btnSearch', event);" style="width:250px;">
    <option value="UK_P">01 net</option>
    <option value="UKA_P">01 net - Hors-série</option>
    <option value="QAA_P">2 Rives, Les (Sorel-Tracy, QC)</option>
    <option value="WV_P">24 Heures (Suisse)</option>
    <option value="FJ_P">Abitibi Express Rouyn-Noranda/Abitibi-Ouest</option>
   (...)

以及“搜索”按钮的html:

 <input type="image" name="btnSearch" id="btnSearch" src="/images/interface/buttons/SearchFR_on.gif" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;btnSearch&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, false))">

下面是我的Python代码的样子:

selectBox = browser.find_element_by_name("lbSources")
selectBox.send_keys("UK_P")
browser.find_element_by_name("btnSearch").click()

所以它首先选择一个框,然后。。。没什么


Tags: nameid元素netvaluehtml按钮option
2条回答

使用“选择类”从下拉列表中单击:

select = Select(driver.find_element_by_id('lbSources'))

# select by visible text
select.select_by_visible_text('UK_P')

# select by value 
select.select_by_value('1')

可以使用直接xpath选择列表选项,然后在列表框上触发onkeypress事件

item = driver.find_element_by_xpath("//select[@id='lbSources']/option[@value='UK_P']")
# click on the list item
item.click()
# now trigger onKeyPress event
list_box = driver.find_element_by_xpath("//select[@id='lbSources']")
driver.execute_script("arguments[0].dispatchEvent(new Event('onkeypress', {'bubbles': true,'cancelable': true}));",list_box)

相关问题 更多 >