如何在url中单击文本为“GET ROUTES”的元素https://maps.mapmyindia.com/direction使用Selenium和Python?

2024-10-04 03:28:29 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用Python单击selenium在“https://maps.mapmyindia.com/direction”上的“get routes”?谢谢你的帮助!你知道吗

我试过什么? 我遵循了这个“python selenium click on button”,但它没有点击。你知道吗

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

driver = webdriver.Firefox(executable_path=r'C:\Users\User\Desktop\pyCode\geckodriver-v0.21.0-win64\geckodriver.exe')
driver.get("https://maps.mapmyindia.com/direction")
startLocation = driver.find_element_by_id("auto_start")
startLocation.send_keys("28.4592,77.0727")
endLocation = driver.find_element_by_id("auto_end")
endLocation.send_keys("28.4590,77.0725")

driver.find_element_by_css_selector('div.col-xs-6.pull-right.text-right').click()

Tags: fromhttpsimportcomgetbydriverselenium
2条回答

要在https://maps.mapmyindia.com/direction上单击文本为GET ROUTES的元素,您需要:

  • 诱导WebDriverWait,使元素容器出现在HTML DOM中。你知道吗
  • 然后需要删除属性style="display: none;"
  • 最后,您可以发送字符序列并对文本为GET ROUTES的元素调用click()方法。你知道吗
  • 代码块:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    driver=webdriver.Firefox(executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
    driver.get("https://maps.mapmyindia.com/direction")
    search_tab = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.CSS_SELECTOR, "div.tab-pane.fade.in.search-tab.active")))
    driver.execute_script("arguments[0].removeAttribute('style')", search_tab)
    driver.find_element_by_css_selector("input.form-control.as-input#auto").send_keys("28.4592,77.0727")
    driver.find_element_by_css_selector("input.form-control.as-input#auto_end").send_keys("28.4590,77.0725")
    driver.find_element_by_css_selector("h2.get-btn>a.get-route#get_d").click()
    
  • 浏览器快照:

map_my_india

我查看了页面,似乎“获取路由”按钮有一个与之关联的id。你可以用这个

所以代码的最后一行应该是:

driver.find_element_by_id("get_d").click()

也可以使用其他选择器:

xpath: //a[text()='Get routes']
css: #get_d

编写测试脚本时,在将选择器包括在测试脚本中之前,始终可以验证浏览器中的选择器。下面是验证选择器的几种简单方法:

  1. 使用“id”时,只需在浏览器控制台中使用以下javascript:document.getElementById("get_d")。如果您使用的id有效,则应该在浏览器控制台中返回一个元素。你知道吗
  2. 使用“xpath”时,请使用浏览器控制台中的$x("//a[text()='Get routes']")行。这还将返回与您提到的xpath相关联的所有元素
  3. 使用“css selector”时,请使用以下行:$$("#get_d")。与xpath方法类似,这将返回与您提到的css选择器相关联的所有元素

相关问题 更多 >