使用 Python 和 Selenium 處理頁面中靜態下拉列表有哪些方法?


在 Selenium 中處理頁面上的靜態下拉列表有多種方法。靜態下拉列表是網頁的重要組成部分。這種型別的 UI 元素通常用於頁面上的生日或年齡選擇。

下拉列表不是單獨的元素。它是一組元素。例如,對於出生日期的選擇,我們需要為日期、月份和年份選擇多個選項。因此,方法是首先獲取主元素,然後轉到其子元素進行選擇。

Selenium API 提供了 Select 類,它可以處理頁面上的靜態下拉列表。我們需要匯入 selenium.webdriver.support.select.Select 來處理 HTML 程式碼中包含 select 標籤的靜態下拉列表。

語法

Select(driver.find_element_by_tag_name("select"))

Select 類下的方法如下所示:

  • **select_by_visible_text(args)** - 透過顯示的選項文字進行選擇。

    此方法是最簡單的方法,它根據可見文字選擇選項。如果不存在與引數中給定文字匹配的選項,則會丟擲 NoSuchElementException 異常。

**語法** -

d = Select(driver.find_element_by_id("selection"))
d.select_by_visible_text('Tutorialspoint')
  • **select_by_index(args)** - 透過選項的索引進行選擇。

    此方法根據特定選項的索引選擇選項。元素的索引通常從 0 開始。如果不存在與引數中給定索引匹配的索引,則會丟擲 NoSuchElementException 異常。

**語法** -

d = Select(driver.find_element_by_id("selection"))
d.select_by_index(1)
  • **select_by_value(args)** - 透過選項的值進行選擇。

    此方法根據特定選項的值選擇選項。如果不存在與引數中給定值匹配的值,則會丟擲 NoSuchElementException 異常。

**語法** -

d = Select(driver.find_element_by_id("selection"))
d.select_by_value('Selenium')
  • **deselect_by_value(args)** - 透過選項的值進行取消選擇。

    此方法根據特定選項的值取消選擇選項。如果不存在與引數中給定值匹配的值,則會丟擲 NoSuchElementException 異常。

**語法** -

d = Select(driver.find_element_by_id("selection"))
d.deselect_by_value('Selenium')
  • **deselect_by_index(args)** - 透過選項的索引進行取消選擇。

    此方法根據特定選項的索引取消選擇選項。元素的索引通常從 0 開始。如果不存在與引數中給定索引匹配的索引,則會丟擲 NoSuchElementException 異常。

**語法** -

d = Select(driver.find_element_by_id("selection"))
d.deselect_by_index(1)
  • **deselect_by_visible_text(args)** - 透過顯示的選項文字進行取消選擇。

    此方法是最簡單的方法,它根據可見文字取消選擇選項。如果不存在與引數中給定文字匹配的選項,則會丟擲 NoSuchElementException 異常。

**語法** -

d = Select(driver.find_element_by_id("selection"))
d.deselect_by_visible_text('Tutorialspoint')
  • **deselect_all()** - 取消選擇所有選定的選項。

    此方法適用於可以進行多個選項選擇的情況。它會移除下拉列表中所有選定的選項。如果無法從下拉列表中選擇多個選項,則會丟擲 NotImplementedError 異常。

**語法** -

d = Select(driver.find_element_by_id("selection"))
d.deselect_all()
  • **all_selected_options()** - 所有選定選項的列表。

    此方法適用於可以進行多個選項選擇的情況。它會返回 select 標籤下所有選定選項的列表。

**語法** -

d = Select(driver.find_element_by_id("selection"))
o = d.all_selected_options()
  • **first_selected_option()** - 返回第一個選定的選項。

    此方法會返回下拉列表中當前選定的選項。它也適用於多選下拉列表,在這種情況下,它會返回下拉列表中第一個選定的選項。

**語法** -

d = Select(driver.find_element_by_id("selection"))
o = d.first_selected_option()
  • **options()** - 所有選項的列表。它會返回 select 標籤下所有選項的列表。

**語法** -

d = Select(driver.find_element_by_id("selection"))
o = d.options()

更新於: 2020-07-29

222 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告