在Python中管理多个Selenium实例
我正在尝试同时管理多个Selenium实例,但一直没能成功。我不太确定这是否可行。我有一个用PyQT做的图形界面应用,它可以从我们的SQL数据库中获取客户的信息。这个应用比较简单,用户可以轻松地登录和退出客户的账户。他们只需点击客户的名字,按下“登录”按钮,就会启动一个Firefox实例,登录到账户,并保持打开状态,用户可以在里面做他们需要做的事情。当他们完成后,点击“注销”按钮,就会退出账户并关闭webdriver实例。
我想提供一种方法,让他们能够同时登录多个账户,同时还能在已登录的客户名称上点击,处理该账户的注销,并关闭那个浏览器实例。
我希望能通过进程ID或唯一ID来控制webdriver,这样我就可以把它存储在一个字典里,链接到那个客户。这样,当他们在应用中点击客户的名字并按下注销时,就可以用类似“client_name = self.list_item.currentItem().text()”的方式获取他们选择的客户名称(我也在用这个做其他事情),然后找到唯一ID或进程ID,发送注销命令给那个实例,然后关闭它。
这可能不是最好的方法,但这是我能想到的唯一办法。
补充:我知道可以通过driver.session_id获取Selenium的session_id(假设你的webdriver实例被命名为'driver'),但到目前为止,我还没看到过如何通过这个session_id来控制webdriver实例。
补充2:这是我目前代码的一个非常简化的版本:
from selenium import webdriver
from PyQt4 import QtGui, QtCore
class ClientAccountManager(QtGui.QMainWindow):
def __init__(self):
super(ClientAccountManager, self).__init__()
grid = QtGui.QGridLayout()
# Creates the list box
self.client_list = QtGui.QListWidget(self)
# Populates the list box with owner data
for name in client_names.itervalues():
item = QtGui.QListWidgetItem(name)
self.client_list.addItem(item)
# Creates the login button
login_btn = QtGui.QPushButton("Login", self)
login_btn.connect(login_btn, QtCore.SIGNAL('clicked()'), self.login)
# Creates the logout button
logout_btn = QtGui.QPushButton("Logout", self)
logout_btn.connect(logout_btn, QtCore.SIGNAL('clicked()'), self.logout)
def login(self):
# Finds the owner info based on who is selected
client_name = self.client_list.currentItem().text()
client_username, client_password = get_credentials(client_name)
# Creates browser instance
driver = webdriver.Firefox()
# Logs in
driver.get('https://www.....com/login.php')
driver.find_element_by_id('userNameId').send_keys(client_username)
driver.find_element_by_id('passwordId').send_keys(client_password)
driver.find_element_by_css_selector('input[type=submit]').click()
def logout(self):
# Finds the owner info based on who is selected
client_name = self.client_list.currentItem().text()
# Logs out
driver.get('https://www....com/logout.php')
# Closes the browser instance
driver.quit()
def main():
app = QtGui.QApplication(sys.argv)
cpm = ClientAccountManager()
cpm.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
1 个回答
你可以使用多个浏览器驱动。只需要多次调用 webdriver.Firefox()
,并保存每个驱动的引用。有些人说会出现一些奇怪的情况,但大体上是可以正常工作的。
driver.close()
这个命令会关闭浏览器,而且不需要传入任何标识符。