【问题标题】:How to check if auto suggestion exists?如何检查是否存在自动建议?
【发布时间】:2019-04-22 13:27:37
【问题描述】:

我需要检查是否存在带有搜索建议的窗口。当您在搜索中键入内容时,会出现建议搜索列表。我需要检查这个弹窗是否存在。

That window

代码试验:

import time
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException

class YandexSearchRu(unittest.TestCase):

def setUp(self):
    self.driver = webdriver.Chrome()

def test_search(self):
    driver = self.driver
    driver.get("http://www.yandex.ru")
    try:
        input = driver.find_element_by_xpath("//*[@id='text']")
    except NoSuchElementException:
        driver.close()
    input.send_keys("Тензор")
    input.send_keys(Keys.RETURN)
    time.sleep(5)

def tearDown(self):
    self.driver.close()

if __name__ == "__main__":

unittest.main()

【问题讨论】:

  • 请修复您的代码...大部分代码实际上并未格式化为代码。建议窗口只是 HTML。如果存在,它可能具有存在的顶级元素。检查该元素的可见性。
  • 提供您尝试选择的页面和元素的 HTML。为您的问题添加适当的描述并检查how to ask

标签: python-3.x selenium webdriver autosuggest webdriverwait


【解决方案1】:

尝试这样做:

driver.get("http://www.yandex.ru")
try:
    input = driver.find_element_by_xpath("//*[@id='text']")
    input.send_keys("adfadf")
    popup = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "body > div. i-bem.popup > div.popup__content")))
    if popup.is_displayed():
        print("popup disyplayed")
    else:
        print("popup not visible")
except NoSuchElementException:

【讨论】:

    【解决方案2】:

    元素不是弹出窗口,而是自动建议,要提取自动建议,您可以使用以下解决方案:

    • 代码块:

      from selenium import webdriver
      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.common.by import By
      from selenium.webdriver.support import expected_conditions as EC
      
      options = webdriver.ChromeOptions()
      options.add_argument('start-maximized')
      options.add_argument('disable-infobars')
      options.add_argument('--disable-extensions')
      driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\WebDrivers\chromedriver.exe')
      driver.get('http://www.yandex.ru')
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.input__control.input__input"))).send_keys("Тензор")
      print([auto_suggestion.text for auto_suggestion in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "div.popup__content>div.suggest2__content.suggest2__content_theme_normal li>span.suggest2-item__text")))])
      
    • 控制台输出:

      ['тензор', 'тензор официальный сайт', 'тензор техподдержка', 'тензорное исчисление', 'тензор спб', 'тензорные ядра', 'тензорный анализ', 'тензор эцп', 'тензорезистор', 'тензор инерции']
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-21
      • 2022-01-02
      • 1970-01-01
      • 2019-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多