首页 > 解决方案 > 如何从谷歌的位置输入字段中选择一个项目

问题描述

Helo,每当我输入谷歌位置下拉菜单时,我无法验证它,我必须点击一个不适合我的选项。

这就是我所指的:https ://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/places-autocomplete

let modal1 = element(by.className('classname'));

await modal1.element(by.css('[role = "combobox"]')).sendKeys("location");

我试过发送向下箭头和回车,但不幸的是它不起作用,请忽略睡眠,只有在那里我可以测试它:


   await modal1.element(by.css('[role = "combobox"]')).sendKeys(protractor.Key.DOWN_ARROW);
   browser.sleep(2000);
   await modal1.element(by.css('[role = "combobox"]')).sendKeys(protractor.Key.ENTER);
   browser.sleep(2000);

我不想将鼠标移动到某个位置。并点击我认为这是一个相当糟糕的解决方案,如果有人知道一些优雅的东西,请发布它

标签: typescriptprotractor

解决方案


伙计,我知道斗争。这是我解决这个问题的方法:

  1. 第一个问题是定位元素。定位器总是在变化。每个下拉菜单都单独附加到 HTML,并且在您关闭后不会被删除。这就是为什么您不能只说“使用与定位器匹配的第一个匹配项”
  2. 第二个问题是实际逻辑。有时您键入时,位置下拉菜单未预先填充。所以你必须重试。老实说,这是我的框架中最丑陋的解决方案,但它做了它应该做的事情
class Common {

    constructor() {

        /**
         * Elements
         */
        this.$locationDropdownContainer = element.all(by.xpath('//div[contains(@class,"pac-container") and not(contains(@style,"width: 0px")) and not(contains(@style,"display: none"))]')).last();
        this.$locationInput = $("#location");
        this.$$locationOptions = $$(".pac-container .pac-item .pac-item-query");
    }

    /**
     * Types provided location and selects the first option
     * @param criteria
     * @param [retry=true] retry on failure
     * @returns
     */
    async enterLocation(criteria, retry = true) {

        log(`enterLocation(${criteria},${retry})`);
        await browser.sleep(350);
        await sendKeys(this.$locationInput, criteria);
        await browser.sleep(400);
        try {
            await browser.wait(ExpectedConditions.visibilityOf(this.$locationDropdownContainer));
        } catch (e) {
            await this.$locationInput.click();
            try {
                await browser.wait(ExpectedConditions.visibilityOf(this.$locationDropdownContainer));
            } catch (e) {
                if (retry) {
                    this.enterLocation(criteria, false);
                }
            }
        }
        await this.$$locationOptions.get(0).click();
        await browser.sleep(350);
    }
}

wheresendKeys只是一个自定义的打字方法,你可以使用input.sendKeys()

AndwaitUntilElementHasAttribute是一种等待元素在属性中具有特定子字符串的方法。在这种情况下,位置下拉容器(包装器元素)不应具有包含“显示:无”的“样式”属性

从 JSDoc 描述中可以看出,我选择了第一个选项,但可以找到一种选择特定选项的方法


推荐阅读