2012-02-17 119 views
1

爲什麼我的代碼:硒蟒蛇被困在這條線

self.driver.find_element_by_xpath("//*[text()[contains(.,'%s')]]" % ('Sorry')) 

卡住,不會通過這條線?即使我做這樣的事情:

driver.implicitly_wait(30) 
self.driver.find_element_by_xpath("//*[text()[contains(.,'%s')]]" % ('Sorry')) 

完整代碼:

# gets stuck here 
if self.is_text_present('Hello'): 
    print 'Hello' 

# rest of code 

def is_text_present(self, text): 
    try: 
     self.driver.find_element_by_xpath('//*[contains(text(), "%s")]' % (text)) 
    except NoSuchElementException, e: 
     return False 
    return True 
+0

您能提供您正在執行此操作的頁面源代碼嗎? – ohaal 2012-02-17 20:37:27

回答

1

你的XPath可以簡化爲

"//*[contains(text(),'%s')]" % ('Sorry') 

也許你可以試試:

import contextlib 
import selenium.webdriver as webdriver 
import selenium.webdriver.support.ui as ui 

with contextlib.closing(webdriver.Firefox()) as driver: 
    ... 
    # Set up a WebDriverWait instance that will poll for up to 10 seconds 
    wait = ui.WebDriverWait(driver, 10) 
    # wait.until returns the value of the callback 
    elt = wait.until(
     lambda driver: driver.find_element_by_xpath(
      "//*[contains(text(),'%s')]" % ('Sorry') 
      )) 

the docs

This waits up to 10 seconds before throwing a TimeoutException or if it finds the element will return it in 0 - 10 seconds.


爲了調試,你可以嘗試正確調用find_element_by_xpath,所以你可以看到司機是看到之前保存的HTML源文件中的問題。該XPath是否對該HTML有效?

def is_text_present(self, text): 
    with open('/tmp/debug.html', 'w') as f: 
     time.sleep(5) # crude, but perhaps effective enough for debugging here. 
     f.write(driver.page_source) 
    try: 
     self.driver.find_element_by_xpath('//*[contains(text(), "%s")]' % (text)) 
    except NoSuchElementException, e: 
     return False 
    return True 
+0

ui.WebDriverWait中的ui是什麼? – 2012-02-17 21:06:55

+0

我忘記了包括進口聲明。編輯... – unutbu 2012-02-17 21:08:32

+0

我得到這個錯誤: Traceback(最近一次調用最後一次): test_add_user中的文件「users.py」,第49行 wait.until(lambda driver:driver.find_element_by_xpath('/ * [contains(文本(),「%s」)]'%('Hello'))) 文件「/Library/Python/2.7/site-packages/selenium/webdriver/support/wait.py」,第55行,直到 raise TimeoutException() TimeoutException:消息:無 – 2012-02-17 21:13:18