python Selenium : get values from dropdown list

标签 python selenium

我在 Python 中使用 Selenium 打开网页,并试图从特定的下拉列表中获取值列表。假设下拉列表的 HTML 代码如下所示:

<select class="mdc-select__input" name="nouveau-num" data-msisdn-loaded="0">                           <option value="" selected="selected"></option>
                     <option value="351 8320175">351 8320175</option>
<option value="351 8652736">351 8652736</option>
<option value="351 8783295">351 8783295</option>
<option value="351 8094085">351 8094085</option>
<option value="351 8861691">351 8861691</option>
<option value="351 8271705">351 8271705</option>
<option value="351 8970191">351 8970191</option>
<option value="351 8965848">351 8965848</option>
<option value="351 8353924">351 8353924</option>
<option value="351 8988158">351 8988158</option>
</select>

我想检索 <option> 之间的所有值标签。我试着做一个 browser.page_source它返回网页的 HTML 源代码,然后执行正则表达式(类似 <option value="[0-9 ]*"> )但结果为空。但是由于某些原因,上面的 HTML 代码不在 Selenium 检索的 HTML 页面源代码中。我有什么想法可以用不同的方式处理这个问题/当前的方法有什么问题吗?

最佳答案

您可以创建一个 Select 对象并使用循环遍历选项的数量。

例如:

from selenium.webdriver.support.ui import Select
selector = Select(driver.find_element_by_name("nouveau-num"))
options = selector.options
for index in range(0, len(options)-1):
    print(options[index])

编辑:

我尝试了您提供的链接上的代码,在加载下拉列表的值之前似乎有延迟。另外我忘了选项有一个元素列表,所以你需要指定.text。最重要的是,By.NAME 似乎比 find_element_by_name

效果更好

修改后的代码如下:

from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

dropdown = driver.find_element(By.NAME, "nouveau-num")

selector = Select(dropdown)

# Waiting for the values to load
element = WebDriverWait(driver, 
10).until(EC.element_to_be_selected(selector.options[0]))

options = selector.options
for index in range(1, len(options)-1):
    print(options[index].text)

使用此代码我收到以下结果:

351 8631174
351 8586821
351 8014561
351 8831839
351 8957001
351 8673968
351 8612034
351 8585995
351 8438130

关于 python Selenium : get values from dropdown list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51001909/

相关文章:

Selenium/Ubuntu 的 PHPUnit fatal error

java - 我们如何使用 KLOV(Extent Reports) 将信息发送到 MongoDB AWS?

python - 我收到此错误 "Message: stale element reference: element is not attached to the page document"

python - 将麦克风数据转换为频谱

python - MongoDB 和 Python - 带列表的字典

javascript - 如何使用 Selenium 和 Python 单击文本为(全选)的下拉项

使用 Allure 报告工具生成 Selenium WebDriver 报告

python - 无法从 Django 中的另一个应用程序导入模型

python - SVG 路径操作

python - Matplotlib - 停止动画