我使用这篇文章http://www.autotest.org.ua/first-autotest-with-selenium-webdriver-and-python/,并在PyCharm中创建了项目
代码试用:
from selenium import webdriver
import unittest
from selenium.webdriver.common.keys import Keys
class GoogleSearch(unittest.TestCase):
def setUpp(self):
self.driver = webdriver.Chrome(executable_path="C:\Python37-32\geckodriver-v0.23.0-win64\geckodriver.exe")
self.driver.get('https://www.google.by')
self.driver.maximize_window()
self.driver.implicitly_wait(10)
def test_01(self):
driver = self.driver
input_field = driver.find_element_by_class_name('class="gLFyf gsfi"')
input_field.send_keys('python')
input_field.send_keys(Keys.ENTER)
错误:
FAILED (errors=1)
Error
Traceback (most recent call last):
File "C:\Python37-32\lib\unittest\case.py", line 59, in testPartExecutor
yield
File "C:\Python37-32\lib\unittest\case.py", line 615, in run
testMethod()
File "D:\QA\untitled\test.py", line 13, in test_01
driver = self.driver
AttributeError: 'GoogleSearch' object has no attribute 'driver'
Process finished with exit code 1
我不知道如何解决...
答案 0 :(得分:-1)
此错误消息...
AttributeError: 'GoogleSearch' object has no attribute 'driver'
...表示 unittest 出现初始化错误。
我在您的代码块中没有看到任何此类错误,但是setUp()
方法中存在问题。几句话:
def setUp(self):
: setUp()
是初始化的一部分,该方法将在要在此测试用例类中编写的每个测试函数之前调用。您将setUp(self)
拼写为 setUpp(self)
。webdriver.Chrome()
,则需要通过 chromedriver 的绝对路径,但是您已经提供了 geckodriver 。 / li>
executable_path
时,请通过单引号和原始r
开关提供 Value 。def tearDown(self):
:每个测试方法之后都会调用 tearDown()
方法。这是执行所有清理操作的方法。if __name__ == '__main__':
:此行将__name__
变量设置为值"__main__"
。如果此文件是从另一个模块导入的,则__name__
将被设置为另一个模块的名称。 基于上述几点,您的有效代码块将为:
import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class GoogleSearch(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome(executable_path=r'C:\path\to\chromedriver.exe')
self.driver.get('https://www.google.by')
self.driver.maximize_window()
self.driver.implicitly_wait(10)
def test_01(self):
driver = self.driver
input_field = driver.find_element_by_class_name('class="gLFyf gsfi"')
input_field.send_keys('python')
input_field.send_keys(Keys.ENTER)
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
unittest.main()
您可以在Python + WebDriver — No browser launched while using unittest module