2016-05-20 5 views
2

あるクラスがページで見つかるまで、セレンを待つようにしようとしていますが、いくつかのコードを試しましたが、何も動作していませんでした。Firefoxでセレンを続ける前にクラスが存在するのを待つ

しようとすると、次の次の

while not firefox.find_element_by_css_selector('.but selected'): 
    print "test" 
    time.sleep(1) 

戻り

selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element

しようの

戻り値:

selenium.common.exceptions.InvalidSelectorException: Message: The given selector but selected is either invalid or does not result in a WebElement. The following error occurred: InvalidSelectorError: Compound class names not permitted

私が間違っているとどのようにそれを修正するのです何を任意のアイデア?

答えて

1

次の例を参照してください。この関数は、クラスがDOMに現れるまで待機します。あなたはまた、 '[(@class、 "CLASS_NAME")を含ま] // XPathの/ /その/要素に' をXPathを変更することができます

import time 
... 
... 
def wait_for_class_to_be_available(browser, total_wait=100): 
    try: 
     # Give only one class name, if you want to check multiple classes then 'and' will be use in XPATH 
     # e.g //*[contains(@class, "class_name") and contains(@class, "second_class_name")] 
     elem = browser.find_element_by_xpath('//*[contains(@class, "class_name")]') 
    except: 
     total_wait -= 1 
     time.sleep(1) 
     if total_wait > 1: wait_for_class_to_be_available(browser, total_wait) 

。 どちらかお選びください。いずれかお選びください。

2

explicit-waitsを試すことができます。ここに小さな例があります:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

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 
from selenium.common.exceptions import TimeoutException 


def test(url): 
    wait_for_element = 30 # wait timeout in seconds 
    firefox = webdriver.Firefox() 
    firefox.get(url) 

    try: 
     WebDriverWait(firefox, wait_for_element).until(
      EC.element_to_be_clickable((By.CLASS_NAME, "but selected'"))) 
    except TimeoutException as e: 
     print("Wait Timed out") 
     print(e) 

if __name__ == '__main__': 
    test("http://www.python.org") 
関連する問題