使用 selenium 测试无头 firefox 但它抛出错误

Testing headless firefox using selenium but it is throwing an error

我正在尝试使用 Selenium 测试无头 firefox,下面的代码给出了正确的结果。

From a fresh Ubuntu 14.04 install I did the following

sudo apt-get install python-pip firefox xvfb
pip install selenium pyvirtualdisplay
useradd testuser
And then in a python shell:

from selenium import webdriver
from pyvirtualdisplay import Display
display = Display(visible=0, size=(800, 600))
display.start()
driver = webdriver.Firefox()
driver.get("http://askubuntu.com")
print driver.page_source.encode('utf-8')
driver.quit()
display.stop()

但是,如果在 Django test.py 中使用 class 实现相同的功能,则它无法正常工作并引发错误。

class FirefoxHeadlessTestCase(LiveServerTestCase):
    def setUp(self):
        # start display
        self.display = Display(visible=0, size=(1024, 768))
        self.display.start()
        # start browser
        self.driver = webdriver.Firefox()

    def tearDown(self):
        # stop browser
        self.driver.quit()
        super(FirefoxHeadlessTestCase, self).tearDown()

        # stop display
        self.display.stop()

    # check if this test should be skipped

    def test_example(self):
        # run tests
        print self.driver.get("http://askubuntu.com").page_source.encode('utf-8')

Error: print self.driver.get("http://askubuntu.com").page_source.encode('utf-8') AttributeError: 'NoneType' object has no attribute 'page_source'

有人知道我哪里出错了吗?

问题出在您的链接上。请注意,您的 Django 代码略有不同

 print self.driver.get("http://askubuntu.com").page_source.encode('utf-8')

来自您的其他 python 代码

driver.get("http://askubuntu.com")
print driver.page_source.encode('utf-8')  

不幸的是,驱动程序 get 方法没有 return 任何东西,因此无法像在您的 django 代码中那样进行更改。您将需要像在其他 python 代码中一样的行。