0

您将如何在第一次调用脚本时创建一个实例webdriver,然后在下一次检索相同的实例?像这样的伪代码:

from selenium import webdriver

thisScript = FIXME

if thisScript.isRunning():
    driver = thisScript.driver

else:        
    driver = webdriver.Firefox()

driver.get("http://www.example.com")
4

1 回答 1

0

最好的选择似乎是设置一个服务器/客户端系统,我想它可以使用 selenium 服务器来完成,但我最终编写了自己的代码,如下所示:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
# This script takes a html file name as argument to start the
# selenium webdriver. It will start a server the first time it's run.
# If called again, it will then check if the server is running
# and restart it if neccessary. This prevents from having to restart
# the browser when running tests from different scripts by facilitating
# the running instance of selenium.

import socket, threading, time, commands, os

from selenium import webdriver

dirPath = "/path/to/dir"
fileUri = "/path/to/file"

class ThreadServer(threading.Thread):
    def __init__(self, port=None, host=None):
        threading.Thread.__init__(self)

        self.host = host if host != None else "localhost"
        self.port = port if port != None else self.getFreePort()

        self.driver = webdriver.Firefox()

    def getFreePort(self):
        sock = socket.socket()
        sock.bind(('', 0))

        port = sock.getsockname()[1]

        sock.close()

        return port

    def run(self):
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.bind((self.host, self.port))

        port = server.getsockname()[1]
        print 'Server started successfully {0}'.format(port)

        server.listen(1)
        conn, addr = server.accept()

        while 1:
            try:
                fileUrl = conn.recv(4096)

            except socket.error:
                server.listen(1)
                conn, addr = server.accept()
                continue

            if not fileUrl:
                server.listen(1)
                conn, addr = server.accept()

            else:
                self.driver.get(fileUrl)

host = '127.0.0.1'
port = 44164

if dirPath == "/path/to/dir":
    fileUrl = 'http://localhost/{0}'.format(fileUri.lstrip(dirPath))

    try:
        sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        sock.settimeout(3.0)
        sock.connect((host, port))

    except socket.error:
        threadServer = ThreadServer(port)
        threadServer.start()

        time.sleep(3)

        sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        sock.settimeout(3.0)
        sock.connect((host, port))

    try:
        sock.send(fileUrl)

    except socket.error:
        raise

    else:
        sock.close()
于 2013-02-08T23:58:12.243 回答