如何定位 Selenium 中的元素以在搜索框中搜索 Google Place ID?

问题描述 投票:0回答:2

我试图在 Google Place IDs 网站中找到搜索框,我尝试了 By.ID、By.CLASS_NAME、By.XPATH,但我失败了。

place_id_url = "https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder#maps_places_placeid_finder-typescript"

options = Options()
options.add_experimental_option("detach", True)

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()),
                         options = options)

driver.get(place_id_url)

#target the search input field
searchbox = WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//input[@placeholder='Enter a location']")))
searchbox.clear()

keyword = "Dunham Park"
searchbox.send_keys(keyword)

这里是元素信息

<input id="pac-input" class="controls pac-target-input" type="text" placeholder="Enter a location" autocomplete="off" style="position: absolute; left: 188px; top: 0px;">

"//html/body/div[2]/div/div/div[4]/input"

我也试过这段代码,但也失败了。

place_id_url = "https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder#maps_places_placeid_finder-typescript"

options = Options()
options.add_experimental_option("detach", True)

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()),
                         options = options)

driver.get(place_id_url)

driver.find_element(By.XPATH,"//html/body/div[2]/div/div/div[4]/input").send_keys("Dunham Park" + "\n")
#driver.find_element(By.CLASS_NAME, "controls pac-target-input").send_keys("Dunham Park" + "\n")
#driver.find_element(By.ID, "pac-input").send_keys("Dunham Park" + "\n")

我不确定谷歌是否阻止定位元素以防止抓取或其他东西。如果没有,请告诉我。谢谢。

google-maps selenium-webdriver web-scraping web-crawler htmlelements
2个回答
0
投票

主要问题是您要查找的元素位于 IFRAME 中。在定位元素然后键入之前,您需要将上下文切换到 IFRAME。

注意:从 Selenium 4.6+ 开始,您不再需要管理自己的驱动程序。 DriverManager 会为你做这件事。

我修复了一些其他问题并简化了一些事情。这是经过测试的代码。

driver = webdriver.Chrome()
driver.maximize_window()

url = "https://developers.google.com/maps/documentation/javascript/examples/places-placeid-finder#maps_places_placeid_finder-typescript"
driver.get(url)

keyword = "Dunham Park"
wait = WebDriverWait(driver, 10)
wait.until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR, "iframe[src*='geo-devrel-javascript-samples.web.app']")))
wait.until(EC.visibility_of_element_located((By.ID, "pac-input"))).send_keys(keyword)

driver.quit()

-1
投票

试试下面,你提到的定位器似乎不正确

//input[@placeholder="Search"]

© www.soinside.com 2019 - 2024. All rights reserved.