使用编程式 Web 浏览时无法使用检查元素访问输入字段

Input fields not accessible using inspect element when using programmatic web browsing

当我使用 mechanize 时,selenium 库 运行 a url(在本例中为 "www.maps.google.com"),

Chrome 打开时显示 "Chrome is being controlled by an automated testing software".

但是当我尝试检查元素时,只有一个元素:正文。所有其他输入和按钮均未显示。

我想自动执行查找两个地址之间距离的过程,那么如何解决上述问题?

from selenium import webdriver

driver = webdriver.Chrome(executable_path='C:/chromedriver.exe')
# Go to your page url
driver.get('https://www.google.com/maps')
# Get button you are going to click by its id ( also you could us find_element_by_css_selector to get element by css selector)
button_element = driver.find_element_by_id('searchbox-directions')
button_element.click()
dest_add = driver.find_element_by_class_name("tactile-searchbox-input")
dest_add.send_keys("Agra")
start_add = driver.find_element_by_class_name("tactile-searchbox-input")
start_add.send_keys("Jaipur")

例如,这不起作用。因为,自然没有输入字段,所以没有 class 名称 "tactile-searchbox-input".

的元素

引入 WebDriverWait() 并等待 element_to_be_clickable() 和跟随 css 选择器

driver.get('https://www.google.com/maps')
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.ID,"searchbox-directions"))).click()
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"input[aria-label*='starting point']"))).send_keys("Agra")
WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.CSS_SELECTOR,"input[aria-label*='destination']"))).send_keys("Jaipur")

您需要导入以下库。

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

要点击搜索按钮试试这个。

WebDriverWait(driver,20).until(EC.element_to_be_clickable((By.XPATH,"(//button[@aria-label='Search'])[last()]"))).click()