如何使用Python和Selenium点击页面上的多个下拉列表

How can I click on multiple drop down list on a page with Python and Selenium?

本文关键字:下拉列表 Python 何使用 Selenium      更新时间:2023-09-26

我试图点击页面上的多个下拉列表,但我一直收到一个错误,说我的列表对象没有属性tag_name'。

我的代码

def click_follow_buttons(driver):
    selects = Select(driver.find_elements_by_class_name("jBa"))#jBa
    print selects
    for select in selects:
        select.select_by_index(0)
        driver.find_element_by_class_name("bA").click()

我的回溯

Traceback (most recent call last):
  File "google_follow.py", line 50, in <module>
    if click_follow_buttons(driver) == False:
  File "google_follow.py", line 18, in click_follow_buttons
    selects = Select(driver.find_elements_by_class_name("jBa"))#jBa
  File "/usr/local/lib/python2.7/dist-packages/selenium/webdriver/support/select.py", line 35, in __init__
    if webelement.tag_name.lower() != "select":
AttributeError: 'list' object has no attribute 'tag_name'

Html下拉

<div class="jBa XG">
<div class="ny dl d-k-l" jslog="7128; track:impression">

首先,您使用的是find_elements_by_class_name()方法,该方法将返回与类名而非单个元素匹配的web元素列表

但是,即使使用find_element_by_class_name(),也会得到不同的错误,因为这是与类名匹配的div元素,而不是select元素。

您需要传递给具有select标记名的Select类web元素的构造函数:https://selenium.googlecode.com/git/docs/api/py/webdriver_support/selenium.webdriver.support.select.html

建造师。检查给定元素是否确实是SELECT标记。如果不是,则UnexpectedTagNameException为抛出。