无法为谷歌地图输入选择下拉菜单选项

Unable to select drop down menu option for google maps input?

本文关键字:选择 下拉菜单 选项 输入 谷歌地图      更新时间:2023-09-26

我正在尝试使用Python和Selenium开发一个程序,以自动查找给定半径内的人口的过程。我选择使用一个网站,它将使用半径和地址。我能够输入半径和地址,但是,我需要能够点击下拉菜单中的选项,这是由谷歌地图提供支持的,所以地址以正确的方式格式化,以便谷歌找到地址并将半径放在地图上。

我遇到的问题是,下拉菜单是由浏览器生成的,我无法检查元素。我不确定如何使用Selenium使用Python或Javascript访问元素,以便单击第一个下拉菜单选项。一旦下拉菜单选项被点击,半径将在地图上生成,然后我将能够继续点击计算按钮,以找到半径内的人口。

TLDR:我怎么能点击下拉菜单由谷歌地图与Python或Javascript在硒?无法检查下拉菜单。

网站:https://www.freemaptools.com/find-population.htmPython代码:

def putInputs(driver,address,radius):
    print "Entering inputs:"
    radius_input = "document.getElementById('radiusinputmi').value = " + radius
    driver.execute_script(radius_input)
    driver.find_element_by_id("radiusinputmi").send_keys(radius)
    driver.find_element_by_id("tb_searchlocation").send_keys(address)
    # i need to click on the drop down menu so the radius shows up!
更新:

我发现下拉菜单显示在HTML页面的底部。然而,我仍然不确定如何选择它。我用下面的Javascript代码更接近于选择所需的元素。

Javascript:

// address of location to find
var address = "Indiana University Blooington";
// get input text box
var location_input = document.getElementById("tb_searchlocation");
// set input text box to the address given
location_input.value = address;
// get the drop down menu with the available options given input location
var x = document.getElementsByClassName("pac-container pac-logo")[1];
// make the google maps options drop down visible
x.setAttribute("style","width: 212px; position: absolute; left: 2px; top: 901px;");
// get the first option from the google maps drop down menu
var items = x.getElementsByClassName("pac-item");
// HOW CAN I SELECT THE FIRST DROP DOWN MENU??
// tried:
// items[0].focus();
// items[0].select();
// items[0].click();

这里我将给你一段从下拉菜单中选择第一个值的代码。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
import time
driver =  webdriver.Chrome()
driver.get("https://www.freemaptools.com/find-population.htm")
#driver.find_element_by_id("radiusinputmi").send_keys(radius)
ele  = driver.find_element_by_id("tb_searchlocation")
ele.send_keys("Indiana University Blooington")
time.sleep(10)
ele.send_keys(Keys.DOWN)
ele.send_keys(Keys.RETURN)
time.sleep(10)
driver.quit()