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



我正在尝试更改下拉列表的值,并在从标签和<option>标签中选择值时遇到问题<select>

这是我想改变的 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>

我正在使用网络驱动程序(Chrome(。这是我的代码。

driver.find_element_by_name('frmSearch').find_element_by_id('searchByInput91').click()

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

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)

我该怎么办?

根据您提供的HTML,似乎<select>标签包含样式属性作为显示: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')

相关内容

  • 没有找到相关文章

最新更新