我试图在Google Place id网站上找到搜索框,我试过了。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")
我不确定谷歌是否阻止定位元素以防止爬行或其他东西。如果没有,请告诉我。谢谢。
主要问题是您正在寻找的元素是在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()