Python 3 Selenium:在屏幕上找不到元素

时间:2017-09-07 14:01:52

标签: html python-3.x selenium

我正在尝试使用selenium找到并点击网页上的元素。该网页使用此网页上的内置搜索栏https://www.innisfil.ca/,并通过点击下一个按钮来迭代搜索结果。

下一个按钮存储在span元素中,其中包含“search-next”类,如下面网站的html代码中所示。

<font class="search-nav" face="arial,verdana,geneva,lucida" size="-1">
     <span class="search-prev">&lt;&lt;&nbsp;Prev</span>
     <span class="search-prevnext-sep">&nbsp;&nbsp;|&nbsp;&nbsp</span>
     <span class="search-next">
         <a class="search-nav" dir="ltr" href="https://search.freefind.com/find.html?pageid=r&amp;id=47055328&amp;query=environmental+assessment&amp;sbv=j2&amp;ics=1&amp;fr=10" target="">
             <b>Next</b>
             &nbsp;&gt;&gt;
         </a>
     </span>&nbsp;&nbsp;&nbsp;
</font>

这里是我写的工作示例代码:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException

url ='http://www.town.innisfil.on.ca'
munip = "t"
bar_name = 'query'
search_term = "environmental assessment"
next_button_name = "search-next"

driver = webdriver.Chrome()
driver.get(url)

search_bar = driver.find_element_by_name(bar_name)
search_bar.send_keys("house")
search_bar.send_keys(Keys.RETURN)

try:
     span = driver.find_element_by_class_name(next_button_name)
     span.find_element_by_tag_name("a").click()
except NoSuchElementException:
     print("Can't find next button")

我的问题是为什么我可以在html的屏幕上看到按钮,但是selenium似乎无法找到它?我对html的细节并不十分熟悉,这可能是非常明显的。提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

文字var dbDataSorted = from entry in dbData.AsEnumerable() join user in this.UserManager.Users on entry.UserId equals new Guid(user.Id) orderby user.UserName ascending select entry; return dbDataSorted; 的搜索结果显示在house内,iframeid。因此,您必须先切换到 ffse-overlay-ifr ffse-overlay-ifr。这是您自己的代码,其中包含一些简单的修改,这些修改在我的frame系统上完美运行:

Windows 8

控制台输出:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

url ='http://www.town.innisfil.on.ca'
munip = "t"
bar_name = 'query'
search_term = "environmental assessment"
next_button_name = "search-next"
driver = webdriver.Chrome(executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.maximize_window()
driver.get(url)
search_bar = driver.find_element_by_name("query")
search_bar.send_keys("house")
search_bar.send_keys(Keys.RETURN)
driver.switch_to_frame("ffse-overlay")
driver.find_element_by_xpath("//a[@class='search-nav']").click()
print("Next Button Clicked")