2015-06-07 34 views
3

所以我正在用Python和Selenium進行一些網絡抓取,我遇到了問題。我點擊下一步按鈕移動到某個網站的下一頁,但當我到達最後一頁時,我需要停止點擊它。現在,我的想法就是在try/except語句中使用some_element.click(),並等待它發出錯誤,而按鈕不再可單擊。看起來雖然,.click()不會發出任何類型的信號,但當按鈕不能被點擊時它不會發出錯誤,並且不會發出任何真或假的信號。使用Selenium和Python,如何檢查按鈕是否仍然可點擊?

的代碼片段我試着使用:

while True: 
    try: 
     button = driver.find_element_by_class_name('Next_button') 
     button.click() 
    except: 
     break 

有沒有其他辦法?感謝和歡呼。

+0

是元素顯示當你到達最後一頁? – Saifur

+1

這可能是鏈接仍然是可點擊的,但不會移動到下一頁,它什麼也不做。你能分享到你運行代碼的網站的鏈接嗎? – alecxe

+0

@Saifur是對的。當您重新查看最後一頁時,檢查該按鈕的html屬性更改。 –

回答

5

在不瞭解更多關於您的示例目標的情況下,可以說的最小值是可點擊的屬性具有「href」屬性。
您可以使用元素的get_attribute屬性:

button = driver.find_element_by_class_name('Next_button') 
href_data = button.get_attribute('href') 
if href_data is None: 
    is_clickable = False 

Gets the given attribute or property of the element.

This method will first try to return the value of a property with the given name. If a property with that name doesn’t exist, it returns the value of the attribute with the same name. If there’s no attribute with that name, None is returned.

Values which are considered truthy, that is equals 「true」 or 「false」, are returned as booleans. All other non-None values are returned as strings. For attributes or properties which do not exist, None is returned.

更多關於使用get_attribute

您也可以嘗試is_displayedis_enabled

+1

我很確定這會解決我的問題。我旁邊沒有完整的代碼,但我會盡快進行測試。只有一件小事,班級在最後一頁改名。我會盡快測試代碼。非常感謝。 –

+1

如果您確定類名稱在「最後一頁」上發生更改,您還可以執行檢查以查看具有該類名稱的元素是否存在:http://stackoverflow.com/questions/7991522/selenium-webdriver- test-if-element-is-present –

+0

對不起,花了我這麼久,我不得不重寫代碼,直到那一點(因爲我現在沒有我的應用程序的源代碼)。我想嘗試你的第一個建議,但我有一個新問題。每當我使用find_element_by_class_name時,我收到一個錯誤:「消息:無效的選擇器:複合類名稱不允許」。基本上,因爲班級的名字裏面有一個空格,「下一個拷貝」。任何快速建議?謝謝。 –

3

使用該得到的類 element.getAttribute(「類」) 和chcek如果類列表中包含的特徵類(例如「禁用」)從侑HTML框架,用來描述unclicable按鈕

+0

謝謝,我也會測試一下。我不知道getAttribute()可以以這種方式使用。 –

+0

+1這個答案。 Selenium使用element_to_be_clickable等待函數引入了預期條件,但由於某些未知原因,即使它被禁用,它仍然認爲按鈕可點擊。獲取類屬性並搜索「禁用」爲我解決了它。 – Derorrist

相關問題