AttributeError: 'Select' 对象没有属性 'get_attribute' 错误,使用 select_by_index() 从下拉菜单中选择一个选项,使用 Selenium Python。

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

我是一个python新手,在从下拉表中刮取文本时遇到了一个问题。

这就是问题所在。

from selenium import webdriver
from time import sleep
from selenium.webdriver.support.ui import Select

driver = webdriver.Chrome()
driver.get("https://www.ehail.ca/quotes/?1590984761655")

desired_data =
Select(driver.find_element_by_xpath("/html/body/div[1]/div[2]/form[2]/table[1]/tbody/tr/td/table/tbody[1]/tr[2]/td[10]/select"))

desired_data.select_by_index(1)

print(desired_data.text))

并得到错误的结果。

AttributeError: 'Select' object has no attribute 'get_attribute' 

我也试过 print(desired_data.text) 但在那里没有运气。

硒可以做吗,还是需要另一个库,比如靓汤?

谢谢你的阅读

编辑1: 我已经填写了所需的字段,但仍然得到同样的错误。我可以选择元素,但当我试图打印时,我得到了 <selenium.webdriver.support.select.Select object at 0x087810B8>

python selenium selenium-webdriver drop-down-menu html-select
1个回答
0
投票

呼叫 .first_selected_option 先易后难 .text 方法。

参考文档。

这个选择标签中的第一个选择(或普通选择中的当前选择)。

desired_data.select_by_index(1)
print(desired_data.first_selected_option.text)

它将返回当前选择的选项。


0
投票

你看到的是正确的行为。

在你的程序中,就在调用 get(url) 因为你正在调用 Select(webelement) 所需的班级 WebElement 而不填写前面的必填项,则 <option> 项目不会被填充创建。

no_options

因此当你调用 select_by_index(1) 方法,而该方法又在内部调用 if opt.get_attribute("index") == match: 引起错误。

AttributeError: 'Select' object has no attribute 'get_attribute' 

执行 select_by_index():

def select_by_index(self, index):
    """Select the option at the given index. This is done by examing the "index" attribute of an
       element, and not merely by counting.

       :Args:
        - index - The option at this index will be selected

       throws NoSuchElementException If there is no option with specisied index in SELECT
       """
    match = str(index)
    for opt in self.options:
        if opt.get_attribute("index") == match:
            self._setSelected(opt)
            return
    raise NoSuchElementException("Could not locate element with index %d" % index)

解决办法

填写前面的必填字段,在 <option> 元素将被填充,程序执行成功。

© www.soinside.com 2019 - 2024. All rights reserved.