繁体   English   中英

Selenium和Python的下拉列表

[英]Drop Down for Selenium and Python

我有一个下拉菜单,其来源如下:

<select name="issuer">
<option selected="selected" value="15">MBBTampereRootCA
</option><option value="66222">OMS_CA1
</option><option value="66225">OMS_CA2
</option><option value="71463">stefanSpiel
</option></select>

我需要选择“ stefanSpiel”,请告诉我该怎么做?

我尝试了多种可能的选择,但未成功。

我尝试了以下选项:

browser = webdriver.Firefox()
browser.find_element_by_css_selector("option.stefanSpiel")
browser.find_element_by_link_text('option.stefanSpiel');

还有这些:

'element = browser.find_element_by_name("issuer")'
'target = select (option, stefanSpiel)'
'action_chains = ActionChains(browser)'
'action_chains.drag_and_drop(element, target)'

'ActionChains(browser).move_to_element(element).click(target).perform()'

但是我得到的只是:'selenium.common.exceptions.NoSuchElementException:'

谢谢,

一种方法是单击“选择”元素。 这将“打开”下拉列表,并使所有下拉选项对我们的驱动程序可见。 现在,我们需要单击所需的元素。

例如,让我们看看下面的html(它与您提供的html非常相似)是我从http://www.tizag.com/htmlT/htmlselect.php那里获得的:

<select name="selectionField"> 
  <option value="CA">California -- CA </option>
  <option value="CO">Colorado -- CO</option>
  <option value="CN">Connecticut -- CN</option>
</select>

对于此示例,我将使用xpaths。 可以说我有'select'元素的xpath:

xpath = '/html/body/table[3]/tbody/tr[1]/td[2]/table/tbody/tr/td/div[4]/select'

我想选择“ Connecticut-CN”选项

一种方法是这样的:

from selenium import webdriver

driver  = webdriver.Firefox()

# navigate to the page that contains the html I provided  
driver.get('http://www.tizag.com/htmlT/htmlselect.php')

# the xpath of the <select> elemnt
xpath = '/html/body/table[3]/tbody/tr[1]/td[2]/table/tbody/tr/td/div[4]/select'

# click on the <select> element to open the dropdown
driver.find_element_by_xpath(xpath).click()

# select the desired option
driver.find_element_by_xpath(xpath+'/*[contains(text(), "Connecticut -- CN")]').click()

我建议您使用存在的Select()类来处理select元素。

from selenium.webdriver.support.select import Select

select_element = Select(driver.find_element_by_name("issuer"))
select_element.select_by_visible_text("stefanSpiel")

谢谢大家...尝试如下,它可以工作...不确定在什么程度上是好的:

element = browser.find_element_by_name("issuer")
element.send_keys('stefanSpiel' + Keys.RETURN)

再次感谢 :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM