硒,无法找到xPath元素
我是一个学习Selenium的初学者,试图构建一个小的Web抓取工具。第一部分是转到该站点,然后单击“按地址搜索”按钮。我从Google Chrome浏览器中的“检查元素”中复制了xPath,但是,使用Selenium查找该元素时,始终抛出“无法定位”错误。
from selenium import webdriver
web_Url = 'http://hcad.org/quick-search/'
driver = webdriver.Firefox(executable_path=r'C:\Users\Jaz\Documents\Python\Modules\geckodriver.exe')
driver.implicitly_wait(10) # this lets webdriver wait 10 seconds for the website to load
driver.get(web_Url)
button = driver.find_element_by_xpath("//*[@id='s_addr']").click()
答案 0 :(得分:1)
您要查找的元素位于iframe中。首先,使用“ driver.switchTo()。frame()”命令切换到iframe,然后尝试查找该元素。
this article中讨论了有关切换到iframe的更多详细信息。
from selenium import webdriver
web_Url = 'http://hcad.org/quick-search/'
driver = webdriver.Firefox(executable_path=r'C:\Users\Jaz\Documents\Python\Modules\geckodriver.exe')
driver.implicitly_wait(10) # this lets webdriver wait 10 seconds for the website to load
driver.get(web_Url)
element = driver.find_element_by_xpath("//div[@class='c-general']/iframe")
driver.switch_to_frame(element)
driver.find_element_by_xpath("//*[@id='s_addr']").click()
driver.switch_to_default_content()
答案 1 :(得分:-1)
要click()
上文本为按地址搜索的元素,因为所需元素在<iframe>
中,因此您必须:
您可以使用以下解决方案:
代码块:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver = webdriver.Firefox(executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
driver.get("http://hcad.org/quick-search/")
WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@src='https://public.hcad.org/records/quicksearch.asp']")))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#s_addr"))).click()
浏览器快照:
在这里您可以找到有关Ways to deal with #document under iframe的相关讨论