硒蟒卡在这条线上

时间:2012-02-17 20:34:55

标签: python xpath selenium

为什么我的代码:

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

1 个答案:

答案 0 :(得分: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

  

在抛出TimeoutException之前等待最多10秒或者等待   它发现元素将在0-10秒内返回。


要调试问题,您可以尝试在调用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