[英]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.