Python - 如何使用硒从消失的下拉列表中找到元素

Python - How to find an element from a disappearing drop down using selenium

我正在尝试使用 seleniumsteam homepage 上消失的下拉列表中找到一个元素。当您在搜索栏中键入内容时,结果会下拉,如果您在搜索栏外单击,则下拉结果会消失。如果您希望再次显示结果,则需要再次单击它。

无论如何,我的代码在搜索栏中输入了一个输入,当 input_elem.send_keys(game) 运行时,下拉列表 会显示 (我使用“terraria”作为输入),并且每个第一个结果都有相同的 css 选择器。我也尝试用 xpath 找到元素,它也不起作用:

from selenium import webdriver

game = input('Type the game you want to find here: ')

# configure browser
browser = webdriver.Firefox()
browser.get('https://store.steampowered.com/')

# input game
input_elem = browser.find_element_by_css_selector('#store_nav_search_term')
input_elem.send_keys(game)

# click the first result
first_match = browser.find_element_by_css_selector('a.match:nth-child(1)')
first_match.click()

这是完整的错误:

Traceback (most recent call last):
  File "/home/fanjin/Documents/Python Projects/web_projects/steam/game_finder.py", line 14, in <module>
    first_match = browser.find_element_by_css_selector('a.match:nth-child(1)')
  File "/home/fanjin/.local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 598, in find_element_by_css_selector
    return self.find_element(by=By.CSS_SELECTOR, value=css_selector)
  File "/home/fanjin/.local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 976, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "/home/fanjin/.local/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute
    self.error_handler.check_response(response)
  File "/home/fanjin/.local/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: a.match:nth-child(1)

要点击您必须诱导的第一个自动建议 for the element_to_be_clickable() and you can use either of the following :

  • 使用CSS_SELECTOR:

    driver.get("https://store.steampowered.com/")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#store_nav_search_term"))).send_keys("terraria")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div#search_suggestion_contents>a"))).click()
    
  • 使用XPATH:

    driver.get("https://store.steampowered.com/")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='store_nav_search_term']"))).send_keys("terraria")
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='search_suggestion_contents']/a"))).click()
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
  • 浏览器快照:


参考资料

您可以在以下位置找到关于 的一些相关讨论: