Selenium中无法获取下拉框定位器的问题求助
解决KAYAK住宿搜索下拉框定位及回车无效问题
先搞定DevTools调试时下拉框消失的问题
- 打开DevTools后,点击右上角三个点 → More tools → Rendering
- 勾选Emulate a focused page,页面会保持焦点,下拉框就不会因为切换到DevTools而消失,就能正常获取元素定位器了
针对回车无效的解决方案
方法1:直接定位并点击下拉选项
输入地点后,用显式等待确保下拉框加载完成,再定位目标选项点击:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By # 定位输入框并输入地点 location_input = driver.find_element(By.ID, "location-field") location_input.send_keys("New Delhi") # 等待下拉建议列表出现 wait = WebDriverWait(driver, 10) suggestion_list = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "ul[aria-label='Location suggestions']"))) # 点击第一个建议选项 suggestion_list.find_element(By.TAG_NAME, "li").click()
方法2:用方向键选中后回车
如果直接回车无效,试试先按方向键选中选项再回车:
from selenium.webdriver.common.keys import Keys location_input = driver.find_element(By.ID, "location-field") location_input.send_keys("New Delhi") # 等待下拉框出现 WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "ul[aria-label='Location suggestions']"))) # 按向下箭头选中第一个选项,再回车 location_input.send_keys(Keys.ARROW_DOWN) location_input.send_keys(Keys.ENTER)
方法3:通过JavaScript注入触发事件
有些网站的下拉框依赖JS事件,直接输入值可能没触发加载,试试用JS设置值并触发输入事件:
location_input = driver.find_element(By.ID, "location-field") # 用JS设置输入框值 driver.execute_script("arguments[0].value = 'New Delhi';", location_input) # 触发input事件,让网站加载下拉建议 driver.execute_script("arguments[0].dispatchEvent(new Event('input'));", location_input) # 等待后点击选项 WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "ul[aria-label='Location suggestions'] li"))).click()
内容的提问来源于stack exchange,提问作者Prabhu Swain
相关产品推荐
相关产品推荐

