【问题标题】:Unable to select element from Dropdown that hides - Python Selenium无法从下拉列表中选择隐藏的元素 - Python Selenium
【发布时间】:2020-12-01 19:09:05
【问题描述】:

我正在尝试进入搜索结果页面,但我必须先单击下拉选项才能完成搜索。当我手动执行此操作时,如果我没有在它出现时单击它,下拉菜单会隐藏,当我对其进行编码时,我会收到以下错误:

ElementNotInteractableException: Message: Element <div id="_esgratingsprofile_autocomplete-results-container" class="autocomplete-results-container msci-ac-search-data-dropdown"> could not be scrolled into view

这是我目前的代码,你也可以访问 url 看看它是怎样的:

from selenium.webdriver import Firefox
from selenium.webdriver.support.ui import Select
from selenium.webdriver.firefox.options import Options
opts = Options()
opts.set_headless()
assert opts.headless
browser = Firefox(options=opts)
browser.get('https://www.msci.com/esg-ratings')
search_form = browser.find_element_by_id('_esgratingsprofile_keywords')
search_form.send_keys('MSFT')
browser.find_element_by_xpath("//div[@id='_esgratingsprofile_autocomplete-results-container']/ul[@id='ui-id-1']/li[@class='msci-ac-search-section-title ui-menu-item']").click()

我查看了许多其他答案,但他们似乎没有处理下拉菜单不是可直接点击的元素或如果您不立即点击它隐藏的情况。任何帮助表示赞赏。

【问题讨论】:

  • 使用javascriptexecutor执行点击动作
  • @Shrini 即使元素没有滚动到视图中也会起作用吗?

标签: python selenium web-scraping drop-down-menu


【解决方案1】:

试试下面的代码,这个代码对我有用。如果它显示任何错误,请告诉我。

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

driver = webdriver.Chrome()
driver.maximize_window()
wait = WebDriverWait(driver, 5)
action = ActionChains(driver)

driver.get("https://www.msci.com/esg-ratings")

Drop_Down = driver.find_element_by_xpath('//*[@id="_esgratingsprofile_keywords"]')
Drop_Down.send_keys("MSFT")

# Select the First Result from the search.
Result = wait.until(
    EC.presence_of_element_located((By.XPATH, "//div[contains(@class,'autocomplete-results-container')]/ul/li[1]")))
action.move_to_element(Result).click().perform()

【讨论】:

  • 谢谢!这对我有用,并且会接受答案。只是一个问题,有没有办法在不打开浏览器的情况下使用 chrome 来运行它?
  • from selenium import webdriver from selenium.webdriver.chrome.options import Options chrome_options = Options() chrome_options.add_argument("--headless") driver = webdriver.Chrome(options=chrome_options)
  • 从这个线程中获得帮助 - stackoverflow.com/questions/53657215/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多