【问题标题】:Selenium select option硒选择选项
【发布时间】:2014-04-07 04:29:30
【问题描述】:

我有多个选择选项:

<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 年,而没有在 id = auto_make 中寻找 2014 年的选项。任何帮助或建议都会非常有帮助。

【问题讨论】:

  • 您是否尝试过在yearoption.click() 代码之后插入一个小睡眠?这将确保 onclick 方法可以执行。
  • 在自动化脚本中休眠是不明智的,应该避免

标签: python select selenium


【解决方案1】:

两周前我也在为同样的问题苦苦挣扎。我尝试了许多不同的选项,并最终采用了以下方法。问题是 click()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.click()之后执行yearoption_val.send_keys(Keys.RETURN)

**英语不是我的母语。请酌情修改答案

【讨论】:

    【解决方案2】:

    您是否尝试过实例化 Select 对象?这是来自 Selenium 网站的 Python 示例;

    # 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")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-29
      • 2013-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多