Nếu bạn muốn khám phá mã nguồn của trình điều khiển python-selen, bạn sẽ thấy những gì quit()
method của trình điều khiển firefox được thực hiện:
def quit(self):
"""Quits the driver and close every associated window."""
try:
RemoteWebDriver.quit(self)
except (http_client.BadStatusLine, socket.error):
# Happens if Firefox shutsdown before we've read the response from
# the socket.
pass
self.binary.kill()
try:
shutil.rmtree(self.profile.path)
if self.profile.tempfolder is not None:
shutil.rmtree(self.profile.tempfolder)
except Exception as e:
print(str(e))
Có những điều bạn có thể dựa vào đây: kiểm tra profile.path
để tồn tại hoặc kiểm tra trạng thái binary.process
. Nó có thể hoạt động, nhưng bạn cũng có thể thấy rằng chỉ có "cuộc gọi bên ngoài" và có không có gì thay đổi ở phía bên python sẽ giúp bạn chỉ ra rằng quit()
được gọi.
Nói cách khác, bạn cần phải thực hiện một cuộc gọi bên ngoài để kiểm tra tình trạng:
>>> from selenium.webdriver.remote.command import Command
>>> driver.execute(Command.STATUS)
{u'status': 0, u'name': u'getStatus', u'value': {u'os': {u'version': u'unknown', u'arch': u'x86_64', u'name': u'Darwin'}, u'build': {u'time': u'unknown', u'version': u'unknown', u'revision': u'unknown'}}}
>>> driver.quit()
>>> driver.execute(Command.STATUS)
Traceback (most recent call last):
...
socket.error: [Errno 61] Connection refused
Bạn có thể đặt nó dưới try/except
và thực hiện một chức năng tái sử dụng:
import httplib
import socket
from selenium.webdriver.remote.command import Command
def get_status(driver):
try:
driver.execute(Command.STATUS)
return "Alive"
except (socket.error, httplib.CannotSendRequest):
return "Dead"
Cách sử dụng :
>>> driver = webdriver.Firefox()
>>> get_status(driver)
'Alive'
>>> driver.quit()
>>> get_status(driver)
'Dead'
cách tiếp cận khác sẽ được làm cho tùy chỉnh của bạn Firefox webdriver và thiết lập session_id
-None
trong quit()
:
class MyFirefox(webdriver.Firefox):
def quit(self):
webdriver.Firefox.quit(self)
self.session_id = None
Sau đó, bạn chỉ có thể kiểm tra giá trị session_id
:
>>> driver = MyFirefox()
>>> print driver.session_id
u'69fe0923-0ba1-ee46-8293-2f849c932f43'
>>> driver.quit()
>>> print driver.session_id
None
là kiểm tra để chấm dứt tài xế cần thiết trong mã "chất lượng sản xuất"? Nói cách khác, làm cách nào để tôi cân bằng mã chứng minh thực sự so với thời gian cần để chạy tất cả các kiểm tra này? – franklin
@franklin Tôi chưa bao giờ thực hiện kiểm tra chấm dứt trình duyệt khi sử dụng selenium và tôi nghĩ OP chỉ có một trường hợp sử dụng cụ thể tại đây. Không chắc chắn nếu điều này là thực sự cần thiết để chạy sau khi bỏ trình điều khiển. Bạn nghĩ sao? – alecxe
Tôi rất quan tâm, tôi thực sự [hỏi câu hỏi] (http://stackoverflow.com/questions/35426824/optimal-amount-of-testing-for-selenium/) tại đây. Tôi thành thật nghĩ rằng tỷ lệ thất bại của việc phá hủy một đối tượng trong ngôn ngữ _any_ quá thấp đến mức không cần thiết phải kiểm tra. – franklin