从Django运行Selenium时出现超时错误

4 投票
2 回答
1536 浏览
提问于 2025-04-16 12:29

我在用Django运行SeleniumRC的时候遇到了一些麻烦。我可以在Python的命令行里顺利运行Selenium文档里提供的示例代码,也能在Python selenium客户端文档里运行,但一旦我尝试在Django的TestCase或者Django的命令行中运行Selenium,就出现了超时错误。
这是我尝试运行的代码:


from selenium import selenium
from django.test import TestCase

class TestSelenium(TestCase):
    def setUp(self):
        self.verificationErrors = []
        self.selenium = selenium("localhost", 4444, "*firefox", "http://127.0.0.1:8000/")
        self.selenium.start()

    def test_foo(self):
        sel = self.selenium
        sel.open("/")

用命令manage.py test registration.TestSelenium运行时,出现了以下错误:


======================================================================
ERROR: test_testformmaintainsdata (registration.tests.TestSelenium)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/sam/Documents/dev/app/CustomMade/registration/tests.py", line 158, in setUp
    self.selenium.start()
  File "/usr/local/lib/python2.6/dist-packages/selenium/selenium.py", line 189, in start
    result = self.get_string("getNewBrowserSession", start_args)
  File "/usr/local/lib/python2.6/dist-packages/selenium/selenium.py", line 223, in get_string
    result = self.do_command(verb, args)
  File "/usr/local/lib/python2.6/dist-packages/selenium/selenium.py", line 214, in do_command
    response = conn.getresponse()
  File "/usr/lib/python2.6/httplib.py", line 990, in getresponse
    response.begin()
  File "/usr/lib/python2.6/httplib.py", line 391, in begin
    version, status, reason = self._read_status()
  File "/usr/lib/python2.6/httplib.py", line 349, in _read_status
    line = self.fp.readline()
  File "/usr/lib/python2.6/socket.py", line 427, in readline
    data = recv(1)
timeout: timed out

----------------------------------------------------------------------
Ran 1 test in 12.475s

FAILED (errors=1)
Destroying test database 'default'...

奇怪的是,虽然出现了错误,Python停止了运行,但SeleniumRC服务器实际上还是启动了Firefox浏览器,只是我无法继续运行其他的Selenium命令,因为Django已经停止了。这是SeleniumServer的输出:


14:21:48.362 INFO - Checking Resource aliases
14:21:48.369 INFO - Command request: getNewBrowserSession[*firefox, http://127.0.0.1:8000/, ] on session null
14:21:48.372 INFO - creating new remote session
14:21:48.443 INFO - Allocated session a3ea05a3d0eb4956ba69a67583ea49ba for http://127.0.0.1:8000/, launching...
14:21:48.533 INFO - Preparing Firefox profile...
14:21:51.473 INFO - Launching Firefox...
14:21:55.904 INFO - Got result: OK,a3ea05a3d0eb4956ba69a67583ea49ba on session a3ea05a3d0eb4956ba69a67583ea49ba

有没有人有什么想法?

2 个回答

1

这个代码可以用浮点数表示的秒数来设置超时时间:

import socket

from selenium import selenium
from django.test import TestCase

class TestSelenium(TestCase):
    def setUp(self):
        socket.settimeout(30)
        # ...
        self.selenium.start()

可以参考 Python标准库文档

3

如果还有其他人遇到这个问题,我是通过在设置方法中增加我的套接字超时时间来解决的。

撰写回答