【问题标题】:How to select an option from the auto suggestions using Selenium and Python如何使用 Selenium 和 Python 从自动建议中选择一个选项
【发布时间】:2021-04-04 06:59:58
【问题描述】:

Selenium documentation 网站的搜索字段中发送文本后,我正在尝试从自动建议中选择一个选项。但我找不到任何这些建议。

代码试验:

driver.get('https://www.selenium.dev/documentation/en/')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#search-by"))).send_keys("selenium")

自动建议的快照:

谁能帮我选择任何自动建议?

【问题讨论】:

  • 您可以发送完整的文本选项,然后发送回车,或者您可以使用 selenium 运行 javascript。对于这些情况,我更喜欢注入 javascript
  • 我通过在搜索框中输入一些内容并点击Ctrl-Shift-I 以在开发工具中打开检查来获得 Chrome 中自动建议的来源。然后,您可以展开该 div 以查找每个自动建议的 div。
  • 如果我用java给你,你能把它映射到python吗?
  • @WilfredClement 当然,我会接受的。欢迎回答。

标签: python selenium selenium-webdriver autosuggest selenium4


【解决方案1】:

+1 @Moshe Slavin 的回答。 autocomplete-suggestions 是包含所有 autocomplete-suggestion's 的 div

为了捕捉元素,我使用getPageSource()将页面中的元素打印出来。

一旦我弄清楚了元素,下面的其余代码就可以自我解释了

wait.until(ExpectedConditions.elementToBeClickable(By.className("autocomplete-suggestion")));

List<WebElement> abc = driver.findElements(By.className("autocomplete-suggestion"));

String value = "Remote WebDriver client";

List<String> def = new ArrayList<String>();

    for (int i = 0; i < abc.size(); i++) {

            //Get the values and store it in a list
            def.add(abc.get(i).getAttribute("data-title"));

        }

        if (def.contains(value))

            abc.get(def.indexOf(value)).click();

        else
            System.out.println("Value not present");

【讨论】:

    【解决方案2】:

    autocomplete-suggestions 是包含所有autocomplete-suggestiondiv

    这里是元素的片段

    为了捕捉元素,我在搜索 selenium 时使用了f8 按钮,这样元素就不会消失。

    这是可视化的代码片段:

    def highlight_element(element):
        driver_elem = element.parent
    
        def apply_style(s):
            driver_elem.execute_script("arguments[0].setAttribute('style', arguments[1]);",
                                       element, s)
    
        original_style = element.get_attribute('style')
        apply_style("background: yellow; border: 2px solid red;")
        sleep(0.5)
        apply_style(original_style)
    
    driver.get("https://www.selenium.dev/documentation/en/")
    WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#search-by")))
    driver.find_element_by_css_selector("#search-by").send_keys("selenium")
    WebDriverWait(driver,30).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, ".autocomplete-suggestions  .autocomplete-suggestion")))
    for ele in driver.find_elements_by_css_selector(".autocomplete-suggestions  .autocomplete-suggestion"):
        highlight_element(ele)
    

    【讨论】:

      猜你喜欢
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      • 1970-01-01
      • 2015-07-07
      • 1970-01-01
      • 2020-09-17
      • 2023-03-28
      相关资源
      最近更新 更多