You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Selenium从指定网站的Licensee Name下拉列表选择指定元素

解决Licensee Name下拉框元素选择问题

你的代码没生效,核心原因是没走对Select2动态下拉组件的交互流程——这类下拉框需要先展开选项面板,才能激活内部的搜索输入框,直接定位输入框操作往往会因为组件未激活而失效。试试以下步骤:

  • 先定位并点击Licensee Name对应的下拉按钮,触发选项面板展开
  • 等待搜索输入框加载完成后,输入目标名称
  • 等待匹配的选项出现,点击完成选择

示例代码(基于Selenium):

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

# 初始化驱动(根据你使用的浏览器调整)
driver = webdriver.Chrome()
driver.get("https://www.mga.org.mt/licences/")

try:
    # 等待并点击Licensee Name的下拉按钮(通过关联标签精准定位目标组件)
    dropdown_btn = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, "//label[text()='Licensee Name']/following-sibling::div//span[@class='select2-selection__arrow']"))
    )
    dropdown_btn.click()

    # 等待搜索输入框加载并输入目标名称
    search_input = WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.XPATH, "//input[@class='select2-search__field']"))
    )
    search_input.send_keys("1x2 NETWORK MALTA LTD")

    # 等待匹配选项出现并点击选中
    target_option = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, f"//li[contains(text(), '1x2 NETWORK MALTA LTD')]"))
    )
    target_option.click()

finally:
    # 可根据需求选择关闭浏览器或保留
    # driver.quit()
    pass

关键注意点:

  • 必须用WebDriverWait等待元素加载,避免因页面异步渲染导致的元素未找到问题
  • 若页面存在多个Select2组件,一定要通过父元素特征(如Licensee Name标签)精准定位目标下拉框,避免误操作其他组件
  • 如果匹配选项的文本不完全一致,可调整XPath的匹配逻辑,比如用contains()或starts-with()模糊匹配

内容的提问来源于stack exchange,提问作者Mohamed Hedeya

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 15:55:20