Selenium Python脚本中的错误

1 投票
3 回答
1976 浏览
提问于 2025-04-16 09:45

我正在学习Python和Selenium RC,但在运行下面这个示例Selenium Python脚本时遇到了一些困难。我已经解决了代码中的所有错误,只剩下一个:

from selenium import selenium
import unittest

class SignUpTask(unittest.TestCase):
    """ The following needs to have the issues corrected to make 
        it run. When the run is completed the answer for question 
        2 will be shown"""

def setUp(self):
    self.selenium = selenium("localhost", 4444, "*firefox",
            "http://www.google.com/")
    self.selenium.start()


def test_that_will_print_out_a_url_as_answer_for_task(sel):
    self.selenium.open("/")
    self.selenium.click("link=Web QA")
    self.selenium.wait_for_page_to_load("30000")
    self.selenium.click("link=Get Involved")
    self.selenium.wait_for_page_to_load("30000")
    url = self.selenium.get_attribute("//ol/li[5]/a@href")
    print """The Url below needs to be entered as the answer 
             for Question 2) in the signup task"""
    print "URL is: %s" % url

def tearDown(self):
    self.selenium.stop()

if __name__ == "__main__":
    unittest.main()

在通过Selenium RC运行上面的脚本后,我收到了以下错误信息:


错误:test_that_will_print_out_a_url_as_answer_for_task (main.SignUpTask) 追踪(最近的调用最后): 文件 "/Users/eanderson/Desktop/TestFiles/Selenium1.py",第16行,在 test_that_will_print_out_a_url_as_answer_for_task self.selenium.open("/") NameError: 全局名称 'self' 未定义

运行了1个测试,耗时24.577秒

失败(错误=1)


有没有人能理解为什么我在第16行会出现

NameError: 全局名称 'self' 未定义

这个错误,并且能帮我解决这个问题,让我的脚本可以顺利运行而不出错?

3 个回答

0

是不是“sel”少了个“f”呢?

def test_that_will_print_out_a_url_as_answer_for_task(sel):

1

调试这类问题的第一步是相信错误信息是正确的。字面意思来看,它说“self没有定义”。所以你要问自己,为什么它没有被定义呢? 其实原因可能只有几种:要么你真的没有定义它,要么你以为你定义了,但实际上没有(这可能是拼写错误,或者你在错误的范围内定义了它)。

那么,“self”是在哪里定义的呢?在Python中,它是作为一个参数传入的。所以,看看那个函数的参数列表。当你查看时,你会发现你把self拼写成了sel

3

这个代码定义了一个叫做 test_that_will_print_out_a_url_as_answer_for_task 的函数,它需要一个参数 sel。不过,这里应该用 self,也就是指代这个类的实例。

撰写回答