2017-09-07 111 views
2

我試圖找到並單擊使用硒的網頁上的元素。該網頁是https://www.innisfil.ca/,使用此網頁上的內置搜索欄並通過單擊下一個按鈕遍歷搜索結果。Python 3 Selenium:找不到在屏幕上可見的元素

下一個按鈕存儲在類別爲「search-next」的span元素中,如下面網站的一段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屏幕上還硒似乎是無法找到它?我對html的來龍去脈並不熟悉,這可能是非常明顯的。預先感謝您的幫助。

回答

1

文本house的搜索結果顯示在iframeid之間作爲ffse-overlay-ifr。所以你必須先切換到ffse-overlay-ifrframe。這裏是你自己的代碼有一些簡單的修改,其完美的作品我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") 

控制檯輸出:

Next Button Clicked 
+1

感謝您很好的解釋回答! –

+0

@AngeMcAuslan很高興能夠爲您提供幫助。 – DebanjanB

相關問題