[英]Using selenium (python) to select an option from a conditional dropdown
[英]SELECT option from dropdown using Selenium Python
一直在使用 Selenium Python 处理国家/地区下拉列表;
这是下拉菜单的 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 class="mat-select-min-line ng-tns-c95-29 ng-star-inserted">MAROKO</span><!----><!---->
用于 select 的代码是:
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")
output
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
我将不胜感激任何有用的评论。
干杯
特地尝试了这个;
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id="mat-radio-2"]/label/span[1]/span[1][text()='MAROKO']"))).click()
但似乎有语法错误
您只能将 selenium 的Select()
class 用于 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 部件创建了定位器。 也许您需要更新它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.