使用Selenium Python从下拉列表中选择选项

mfpqipee  于 2022-11-24  发布在  Python
关注(0)|答案(1)|浏览(256)

使用SeleniumPython处理国家下拉列表;
下面是下拉菜单的Div标记:
<div cdk-overlay-origin="" class="mat-select-trigger ng-tns-c95-29"><div class="mat-select-value ng-tns-c95-29" id="mat-select-value-1"><span class="mat-select-placeholder mat-select-min-line ng-tns-c95-29 ng-star-inserted"></span><!----><!----></div><div class="mat-select-arrow-wrapper ng-tns-c95-29"><div class="mat-select-arrow ng-tns-c95-29"></div></div></div><!---->
下面是目标选项的Div标记:
<div class="mat-select-value ng-tns-c95-29" id="mat-select-value-1"><!----><span class="mat-select-value-text ng-tns-c95-29 ng-star-inserted" style=""><span class="mat-select-min-line ng-tns-c95-29 ng-star-inserted">MAROKO</span><!----><!----></span><!----></div><div class="mat-select-arrow-wrapper ng-tns-c95-29"><div class="mat-select-arrow ng-tns-c95-29"></div></div>
这是目标选项的特定Span标记
<span class="mat-select-min-line ng-tns-c95-29 ng-star-inserted">MAROKO</span><!----><!---->
用于从下拉列表中选择选项代码为:

Country=browser.find_element(By.ID, 'mat-select-value-1')
time.sleep(5) 
drop=Select(Country) 
time.sleep(5) 
drop.select_by_visible_text("MAROKO")

输出功率

Exception has occurred: UnexpectedTagNameException
Message: Select only works on <select> elements, not on <div>
  File "C:\Users\test\form.py", line 31, in <module>
    drop=Select(Country)

我选择了drop.select_by_visible_text,因为我认为这是唯一可用的选项!
使用的导入

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

我将感谢任何有益的评论。
干杯
Tried this特别是这个;

WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id="mat-radio-2"]/label/span[1]/span[1][text()='MAROKO']"))).click()

但似乎有语法错误

xtfmy6hx

xtfmy6hx1#

selenium的Select()类只能用于html <select>标签,但是这个下拉菜单是用<div>实现的,所以你可以像处理html元素一样处理它。
首先,您需要单击下拉菜单以展开选项,然后单击所需的选项:

WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.XPATH, '//div[@class="mat-select-trigger ng-tns-c95-29"]'))).click()
WebDriverWait(browser, 10).until(EC.presence_of_element_located((By.ID, 'mat-select-value-1'))).click()

我已经使用你提供的html部分创建了定位器。也许你需要更新它们。

相关问题