如何通过Selenium和Python根据HTML从选项中选择值

2024-05-14 19:35:36 发布

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

我试图更改下拉列表的值,但在从<select>标记和<option>标记中选择值时遇到了问题。在

这是我想更改的HTML。在

<form name="frmSearch" action="" onsubmit="return false;"> <span class="seljs_title "> <input id="searchByInput91" name="searchBy91" type="text" readonly="readOnly" class="m-tcol-c" style="width: 110px;"> <input type="hidden" name="searchBy" value="0" style="display: none;"> </span> <select id="searchBy" name="" class="m-tcol-c" onchange="$('query').focus();" style="width:110px;display:none;"> <option value="0">one</option> <option value="1">two</option> <option value="3">three</option> <option value="4">four</option> <option value="5">five</option> </select> <input type="text" id="query" name="query" style="ime-mode:active" value="" onkeydown="if (event.keyCode == 13) {nhn.search.goSearch(event);clickcr(this, 'sch.bsearch','','',event)}" class="m-tcol-c border-sub text"> <a href="#" onclick="nhn.search.goSearch(event);clickcr(this, 'sch.bsearch','','',event); return false;"> <img src="https://cafe.pstatic.net/cafe4/hidden.gif" width="42" height="21" alt="검색" class="btn-search-green"> </a> </form>

我使用的是Webdriver(Chrome),这是我的代码。在

^{pr2}$

这段代码使我可以单击下拉列表并打开选项。之后,当我使用这个代码时:

from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_id('searchBy'))
select.select_by_value('1').click()

或者

driver.find_element_by_id("searchBy").send_keys("two")

总是会出现错误消息。在

ElementNotVisibleException: Message: element not visible: Element is not currently visible and may not be manipulated   
  (Session info: chrome=69.0.3497.81)   
  (Driver info: chromedriver=2.41.578737 (49da6702b16031c40d63e5618de03a32ff6c197e),platform=Windows NT 10.0.17134 x86_64)

我该怎么办?在


Tags: textnameeventidinputvaluestyletype
1条回答
网友
1楼 · 发布于 2024-05-14 19:35:36

根据您提供的HTML,似乎<select>标记包含style属性,即display:none;。因此,您可以使用以下解决方案来选择一个选项:

from selenium.webdriver.support.ui import Select
# other lines of code
driver.find_element_by_name('frmSearch').find_element_by_id('searchByInput91').click()
element = driver.find_element_by_xpath("//select[@class='m-tcol-c' and @id='searchBy']")
driver.execute_script("arguments[0].removeAttribute('style')", element)
select = Select(driver.find_element_by_xpath("//select[@class='m-tcol-c' and @id='searchBy']"))
select.select_by_value('1')

相关问题 更多 >

    热门问题