Skip to main content
 首页 » 编程设计

python之如何使用 Selenium 从下拉日历中选择日期

2025年05月04日6kevingrace

我有一个下拉日历,我需要使用 Selenium 从中选择一个日期。 我使用 python 作为我的脚本语言。我也是这个 Selenium 的新手。

请您参考如下方法:

对于以下 HTML:

<select id="edit-birthday-day" class="form-select" name="birthday[day]"> 
 <option selected="selected" value="">-</option> 
 <option value="1">1</option> 
 <option value="2">2</option> 
</select> 

使用您可以在 Python 中使用以下脚本:

    sel.select("id=edit-birthday-day", "label=2") 

另请引用Selenium Documentation :

select ( selectLocator,optionLocator ) 
Select an option from a drop-down using an option locator. 
Option locators provide different ways of specifying options of an HTML Select element (e.g. for selecting a specific option, or for asserting that the selected option satisfies a specification). There are several forms of Select Option Locator. 
 
label=labelPattern 
matches options based on their labels, i.e. the visible text. (This is the default.) 
label=regexp:^[Oo]ther 
value=valuePattern 
matches options based on their values. 
value=other 
id=id 
matches options based on their ids. 
id=option1 
index=index 
matches an option based on its index (offset from zero). 
index=2 
If no option locator prefix is provided, the default behaviour is to match on label. 
 
Arguments: 
 
selectLocator - an element locator identifying a drop-down menu 
optionLocator - an option locator (a label by default)