【问题标题】:How to pick the right options in a dropdown menu with Selenium?如何使用 Selenium 在下拉菜单中选择正确的选项?
【发布时间】:2021-11-24 12:03:11
【问题描述】:

这是下拉菜单:

和

默认情况下它位于Range,我希望我的脚本将其移至Custom

我尝试了几种方法,但都停留在滚动菜单上(第二张图片)并且没有选择Custom

到目前为止,这是我的代码:

from selenium import webdriver

from selenium.webdriver.support.select import Select
from selenium.webdriver.support.ui import WebDriverWait     
from selenium.webdriver.common.by import By     
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys

url = 'https://www.mergermarket.com/homepage'
driver.get(url)
deals = driver.find_element_by_xpath('//*[@id="header"]/div/div[2]/nav/ul/li[4]/a')
urldeals = deals.get_attribute("href")
driver.get(urldeals)

body_element = driver.find_element_by_xpath('//*[@id="searchCriteriaSummary"]/div[4]/div/div[2]/div/div[1]/div[2]/div/div/div[1]/div[1]')

custom = driver.find_element_by_xpath('//*[@id="searchCriteriaSummary"]/div[4]/div/div[2]/div/div[1]/div[2]/div/div/div[1]/div[1]')
custom.click()
custom.send_keys('Custom') 
custom.click()
time.sleep(1)

我收到了这个错误:

selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable

编辑2: 我冻结了浏览器的检查器以可视化下拉列表的html并且没有Select

【问题讨论】:

  • 可能是,但也许我做错了?我收到了这个错误:selenium.common.exceptions.UnexpectedTagNameException: Message: Select only works on <select> elements, not on <div>
  • 我编辑了我的帖子
  • 讨厌,在控制台/F12模式下选择下拉菜单。在控制台类型: $0.Click() 下拉应该出现。现在尝试导航到元素下的任何内容以获取真正的 html。也许页面按钮处的一些隐藏元素出现了?
  • F12 模式?你的意思是检查?

标签: python-3.x selenium


【解决方案1】:

完全重写,事实证明这不是一个普通的 Select,我们可以在其中使用 Selenium Select 类。 不同的方法,尝试获取可点击的元素。您的 xPath 很长,我看不到哪个元素是目标。你能试试这些选项吗? 目前您将 sendKeys 发送到一个 div,Selenium 觉得它很奇怪,因为它不是一个文本字段(它应该是一个 Select,但我们需要忍受它)

custom.click()
driver.find_element_by_xpath('//div[@id=""react-select-12-option-0"]').click()
# or this one
custom.find_element_by_xpath('//div[contains(text(), "Custom")]')

【讨论】:

  • 我收到了这个错误:selenium.common.exceptions.UnexpectedTagNameException: Message: Select only works on <select> elements, not on <div>
  • 我编辑了我的帖子
  • 编辑了我的答案,寻找选择并深入挖掘
  • 我编辑了我的帖子,我像你说的那样深入挖掘并没有找到选择
  • 重写了我的答案
猜你喜欢
  • 1970-01-01
  • 2017-10-29
  • 2016-07-28
  • 2018-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-23
相关资源
最近更新 更多