如何使用python从selenium的下拉框中选择项目

问题描述 投票:0回答:1

我正在尝试遍历webscraping的下拉列表,我注意到我的代码没有用完

dropdown = browser.find_element_by_XPATH('//*[@id="department-dropdown"]')
select = Select(dropdown)

select.select_by_value("Accounting")

我收到的错误消息

Traceback (most recent call last):
  File "C:\Users\David\eclipse-workspace\Web_Scrap\setup.py", line 31, in <module>
    dropdown = browser.find_element_by_XPATH('//*[@id="mainContent"]/div[1]/div/div[3]/div/div/span')
AttributeError: 'WebDriver' object has no attribute 'find_element_by_XPATH'

现在我试图选择至少第一个值,但它只是没有成功

The picture provided has the "inspect element" of the dropdown box i'm attempting to cycle through

这似乎有点令人困惑,下拉框元素不是实际列表的一部分,有人可以让我知道这里实际发生了什么?如果我不正确地看着这个。

如果有人对我能做些什么来实现我的目标有任何建议

python-3.x selenium selenium-webdriver xpath dropdown
1个回答
5
投票

你的下拉框是一个css下拉,而不是纯粹由<select><option>标签实现的原生下拉。

下拉选项来自li内部的<ul class="typeahead typeahead-long dropdown-menu",只有在您单击右侧的向下箭头后才会将其附加到页面。

enter image description here

有一个<select>与许多<option>的原因是上面li的属性:data-value创建在这些<option>。您可以认为这些<option>li的数据源。因此<select>在页面上不可见,就像前端后面的数据库提供数据,因此<select>样式设置为display: none,这意味着在页面上不可见。

要充当用户行为,您应该在li中找到并选择ul中的选项,然后单击它以展开所有li。而不是从不可见的<select>中选择选项或更改select显示css值以使其可见,然后从中选择选项。

// click down arrow to expand all options
driver.find_element_by_css_selector(
    ".department-combobox .input-group > span").click();

// search all options
options = driver.find_elements_by_css_selector(
    ".department-combobox .input-group > ul > li")

// print all option text
for(opt in options):
    println opt.text

// select specific option by text
target = 'Anthropology'
driver.find_element_by_css_selector(
    ".department-combobox .input-group > ul")
    .find_element_by_xpath("./li[.="+target+"]")
    .click();
© www.soinside.com 2019 - 2024. All rights reserved.