我正在尝试进入搜索结果页面,但我必须先单击下拉选项以完成搜索。当我手动执行此操作时,如果我未按原样单击它,则该下拉菜单将隐藏,在编写代码时,会出现以下错误:
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()
我浏览了许多其他答案,但是它们似乎并没有处理下拉菜单不是可直接单击的元素的情况,或者如果您不立即单击它会隐藏 的情况。任何帮助表示赞赏。
答案 0 :(得分:2)
尝试以下代码,该代码对我有用。让我知道它是否显示任何错误。
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()