为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

繁星点点滴滴 2023-04-25 15:24:40
我正在尝试使用selenium从steam 主页上消失的下拉列表中找到一个元素。当您在搜索栏中键入内容时,结果会下拉,如果您在搜索栏外单击,则下拉结果会消失。如果您希望结果再次出现,则需要再次单击它。无论如何,我的代码在搜索栏中输入了一个输入,并且在运行时会显示下拉列表input_elem.send_keys(game)(我使用“terraria”作为输入),并且每个第一个结果都有相同的 css 选择器。我也试图用 xpath 找到元素,它也不起作用:from selenium import webdrivergame = input('Type the game you want to find here: ')# configure browserbrowser = webdriver.Firefox()browser.get('https://store.steampowered.com/')# input gameinput_elem = browser.find_element_by_css_selector('#store_nav_search_term')input_elem.send_keys(game)# click the first resultfirst_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)
查看完整描述

1 回答

?
MMMHUHU

TA贡献1834条经验 获得超8个赞

要点击第一个自动建议,您必须为引入WebDriverWaitelement_to_be_clickable()并且您可以使用以下任一定位器策略:


使用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

浏览器快照:

//img3.sycdn.imooc.com/644780590001422806550257.jpg

查看完整回答
反对 回复 2023-04-25
  • 1 回答
  • 0 关注
  • 97 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信