Selenium选择选项

时间:2014-04-07 04:29:31

标签: python select selenium

我有多个选择选项:

<select id="auto_year" class="element" onchange="loadMakes(this.value);" name="auto_year">
 <option value="0000">- Year -</option>
 <option value="2014">2014</option>
 <option value="2013">2013</option>
 <option value="2012">2012</option>
 <option value="2011">2011</option>
</select>

<select id="auto_make" class="element" onchange="loadModels(document.getElementById('auto_year').value, this.value);;" name="auto_year">
 <option value="0000">- Make-</option>
</select>

最初, select id =“auto_make”中的选项为空。但是当我从 select id =“auto_year”中选择其中一个选项时,会出现该选项。我在选择价值方面遇到了问题。我的代码是:

from selenium import webdriver  
from bs4 import BeautifulSoup
import re

browser = webdriver.Firefox()  
browser.get(certain_url)  
html_source = browser.page_source  

yearoption_val = browser.find_element_by_id('auto_year')
for yearoption in yearoption_val.find_elements_by_tag_name('option'):
 if yearoption.text == '- Year -':
  continue
 else:
  yearoption.click()
  itemmake_val = browser.find_element_by_id('auto_make')
  for itemmake in itemmake_val.find_elements_by_tag_name('option'):
   if (itemmake.text == r'\- Make \(\d+ items\) \-' or '- Model -'):
    continue
  else:
   itemmake.click()

代码的问题在于它选择了2014并进入2013年而没有在2014年 id = auto_make 中寻找选项。任何帮助或建议都会非常有用。

2 个答案:

答案 0 :(得分:1)

两周前,我在解决同样的问题。我尝试了许多不同的选项,最后得到了以下方法。问题是click()Select()确实进行了选择但未能设置值。您可能唯一缺少的是向select对象发送密钥。

从selenium.webdriver.common.keys导入密钥

def select_option_from_a_dropdown(self, select_object, option_value):
    """
     To select options in "<select>" in selenium we need to select the option first and then need
    to send ENTER key on the select.
    """
    options = select_object.find_elements_by_tag_name("option")
    for option in options:
        self.log.info(option.text)
        if option.text.upper() == option_value.upper():
            option.click()
    select_object.send_keys(Keys.RETURN)

如果您遇到与我相同的问题,则只需在yearoption_val.send_keys(Keys.RETURN)之后执行yearoption.click()

**英语不是我的第一语言。请根据需要编辑答案

答案 1 :(得分:0)

您是否尝试过实例化Select对象?以下是Python中Selenium站点的示例;

# available since 2.12
from selenium.webdriver.support.ui import Select
select = Select(driver.find_element_by_tag_name("select"))
select.deselect_all()
select.select_by_visible_text("Edam")