javascript - 无法选择谷歌地图输入的下拉菜单选项?

标签 javascript python selenium

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

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

TLDR:如何在 Selenium 中使用 Python 或 Javascript 单击由谷歌地图提供支持的下拉菜单?无法检查下拉菜单。

网站:https://www.freemaptools.com/find-population.htm

Python 代码:

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()

关于javascript - 无法选择谷歌地图输入的下拉菜单选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40207798/

相关文章:

Java Selenium 查找元素(xpath)

javascript - 更改现有事件的引用

javascript - JavaScript 确认框中的取消选项仅返回 true 条件

javascript - 动态匿名 js 函数不起作用

java - 如何使用 Selenium Java 打开 Chrome 浏览器最大化并通过 ChromeOptions 和 addArguments 抑制信息栏

android - Appium - 使用 Chrome 将文件上传到网络 - ERR_ACCESS_DENIED

javascript - 添加内容问题

python - 如何为 Python 2.7 安装 mechanize?

python - 从 Bitmex API json 转换问题读取价格图表

python - 转换(YYYY-MM-DD-HH :MM:SS) date time