Selenium Python包含字符串引用错误

时间:2016-03-31 14:51:03

标签: python-2.7 selenium xpath selenium-webdriver

我正在验证我的元素中是否存在某些文字。该文本包含字符串中的引号。我的方法是断言False。我希望它是真的,因为文本在GUI上。

我没有在字符串中正确包含引号。请问正确的语法是什么?

当我使用调试器检查代码时,它说:

overwritten_element.text = {unicode} u'One or more reports use the \\'default\\'prefix and will be overwritten.  Do you wish to continue?

我的方法是:

def is_save_overwrite_dialog_displayed(self): 
        overwritten_element = self.get_element(By.ID, 'message_dialog_question_content')
        return overwritten_element.text == r"One or more reports use the 'default' prefix and will be overwritten.  Do you wish to continue?"

带引号的字符串是: 一个或多个报告使用“默认”前缀并将被覆盖。你想继续吗?

我试过了

r"One or more reports use the 'default' prefix and will be overwritten.  Do you` wish to continue?"

我尝试过:

r"One or more reports use the \\'default\\' prefix and will be overwritten.  Do you wish to continue?"

HTML是:

<div id="message_dialog_question_content">
<div>One or more reports use the 'default' prefix and will be overwritten.  Do you wish to continue?</div>
</div>

get_element

# returns the element if found
def get_element(self, how, what):
    # params how: By locator type
    # params what: locator value
    try:
        element = self.driver.find_element(by=how, value=what)
    except NoSuchElementException, e:
        print what
        print "Element not found "
        print e
        screenshot_name = how + what + get_datetime_now() # create screenshot name of the name of the element + locator + todays date time.  This way the screenshot name will be unique and be able to save
        self.save_screenshot(screenshot_name)
        raise
    return element

谢谢, 里亚兹

1 个答案:

答案 0 :(得分:0)

创建了一个类似的测试后,它显示问题不在于引号,而在于双重空间。 Spaces in HTML are compacted.

from splinter import Browser


def test_dummy():
    with Browser() as browser:
        browser.visit("http://localhost:8888/index.html")
        elem = browser.find_by_id("message_dialog_question_content")

        compare = r"One or more reports use the 'default' prefix and will be overwritten.  Do you wish to continue?"
        print "length of elem : {}, length of compare : {}".format(len(elem.text), len(compare))

        assert elem.text == compare

以上测试输出,

>       assert elem.text == compare
E       assert 'One or more ... to continue?' == 'One or more r... to continue?'
E         Skipping 60 identical leading characters in diff, use -v to show
E         - rwritten. Do you wish to continue?
E         + rwritten.  Do you wish to continue?
E         ?           +
---------- Captured stdout call ----------
length of elem : 94, length of compare : 95