【问题标题】:How to select any element from the web element with "display: none" attribute using Selenium in Python如何在 Python 中使用 Selenium 从具有“显示:无”属性的 Web 元素中选择任何元素
【发布时间】:2015-01-13 12:13:12
【问题描述】:

我需要从具有display: none 属性的 web 元素中选择任何元素,如下所示:

<div class="some_class">
  <select id="some_id" class="some_select_class" style="display: none;">
    <option value="1" data-isleaf="false" data-catid="3" data-special_message="" data-adtypeid="0">1</option>
    <option value="2" data-isleaf="true" data-catid="4" data-special_message="" data-adtypeid="1">2</option>    
  </select>
</div>

我可以从网络浏览器手动完成,但我需要通过 Python 中的 Selenium 完成。不幸的是,当我有以下代码时:

try:
  element = selenium.webdriver.support.ui.WebDriverWait(driver, 60).until(EC.visibility_of_element_located((By.ID, 'some_id')))
  selenium.webdriver.support.ui.Select(element).select_by_value('1')
except Exception as ex:
  print(ex)

WebDriverWait 抛出异常并提供以下信息:

消息:''

异常类型为selenium.common.exceptions.TimeoutException

如何实现这个元素的交互?在这种情况下如何选择任何元素?

提前致谢。

【问题讨论】:

  • Selenium 不与设置了display: none 的元素交互。它只与可见元素交互。您可以使用execute_script() 来设置select 的值。话虽如此,我怀疑页面上的一些可见元素正在设置select。您可能应该弄清楚它是什么元素,并与之交互。
  • @Richard 在 execute_script 的情况下,不会触发从选择中激活的触发器,因此我将无法看到弹出的新元素,例如

标签: python python-2.7 selenium selenium-webdriver


【解决方案1】:

使用execute_script() 设置该元素的显示属性,然后使用Selenium Select 选择所需的值。

下面的代码应该适合你:

    try:
      selenium.webdriver.support.ui.WebDriverWait(driver, 60).until(EC.visibility_of_element_located((By.ID, 'some_other_id_on_page')))
      selenium.execute_script("document.getElementById('some_id').style.display='inline-block';")
      element = selenium.webdriver.support.ui.WebDriverWait(driver, 60).until(EC.visibility_of_element_located((By.ID, 'some_id')))
      selenium.webdriver.support.ui.Select(element).select_by_value('1')
    except Exception as ex:
    print(ex)

【讨论】:

  • WebDriverWait 会抛出异常,因为 Web 元素并不真正可见
  • 好的。查看更新的代码,对于第一个 WebDriverWait,您可以检查页面上任何其他元素的可见性,以便我们确保网页正确加载,然后我们可以更改 select 标签的显示属性,
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-01
  • 2014-07-06
  • 1970-01-01
  • 1970-01-01
  • 2020-03-05
  • 2020-05-26
相关资源
最近更新 更多