首页 > 解决方案 > Selenium/Python - 键盘无法访问元素

问题描述

我正在尝试自动填写表格。我用 Selenium 录制了一个脚本。

要填充的字段之一是邮政编码。当我开始输入代码时,会打开一个新窗口以建议适当的选项(javascript 自动填充)

我需要选择 ul 的第一项(参见下面的 html)

我对 Selenium 很陌生,虽然我一直在阅读 Selenium/html 文档,但我在这方面完全被困了将近 1 个月......

非常感谢您的支持

我的代码如下,我收到错误消息“键盘无法访问元素

elem = driver.find_element_by_id("location_p")
    elem.send_keys("75")
    first_option = WebDriverWait(driver, 10).until(
    EC.visibility_of_element_located((By.CLASS_NAME, "selected")))
    first_option.send_keys(Keys.RETURN)

**HTML** 

<div id="localisation_left">


<div class="line toDisable">
    <label for="location_p" class="label">Ville ou code postal *</label>
    <div class="field-wrapper location-container">
        <div class="inputWrapper">
            <i id="browserGeoloc" class="icon-geoloc icon-2x blue"></i>
            <div class="loaderGif-small hidden"></div>

                <input class="nude" name="location_p" id="location_p" autocomplete="off" value="Paris 75010" type="text">

                <input name="zipcode" value="" type="hidden">
                <input name="city" value="" type="hidden">
                <script type="text/javascript">
                    var numberOfLocation = 1, numberOfAuthorizedLocation = 1;
                    var cityNewadMultipleLocation = new MultipleLocationNewad('input[name="location_p"]', numberOfLocation, numberOfAuthorizedLocation);
                    cityNewadMultipleLocation.cityAndZipcodeAreSelected = true;
                </script>

            <input name="region" value="" type="hidden">
            <input name="dpt_code" value="" type="hidden">
        </div>
        <ul class="location-list visible" style="top: 43px;">
<li data-region="12" data-dpt-code="75" class="selected">
                <span class="city" title="Paris">Paris</span>&nbsp;<span class="zipcode">75011</span>
            </li>
                    <li data-region="12" data-dpt-code="75">
                <span class="city" title="Paris">Paris</span>&nbsp;<span class="zipcode">75015</span>
            </li>
                    <li data-region="12" data-dpt-code="75">
                <span class="city" title="Paris">Paris</span>&nbsp;<span class="zipcode">75009</span>
            </li>
                    <li data-region="12" data-dpt-code="75">
                <span class="city" title="Paris">Paris</span>&nbsp;<span class="zipcode">75010</span>
            </li>
                    <li data-region="12" data-dpt-code="75">
                <span class="city" title="Paris">Paris</span>&nbsp;<span class="zipcode">75017</span>
            </li>

标签: selenium

解决方案


您可以click选择第一个选项,而不是Enter按键

elem = driver.find_element_by_id("location_p")
elem.send_keys("75")

condition = EC.visibility_of_element_located((By.CSS, 
    "label[for='location_p'] + div ul.location-list > li"))

first_option = WebDriverWait(driver, 15).until(condition)

first_option.click()

推荐阅读