简体   繁体   English

使用 Selenium,Webdriver 在 python 中单独的 function

[英]Using Selenium, Webdriver in a separate function in python

Pyhton 3.8, Selenium 3.1.4.0, pynput 1.6.8 Pyhton 3.8,Selenium 3.1.4.0,pynput 1.6.8

I have a selenium project I'm working on, and it works fine when in one file, but it's getting pretty big 300~ lines.我有一个正在处理的 selenium 项目,它在一个文件中运行良好,但它变得相当大 300~ 行。

I want to separate my project into a main file, and a functions file.我想将我的项目分成一个主文件和一个函数文件。

I know how to do this normally, but when using selenium I am at a bit of a loss, since you use driver.[various things] all over everywhere.我知道如何正常执行此操作,但是在使用 selenium 时,我有点不知所措,因为您到处都在使用驱动程序。[各种东西]。

I am wondering if there is a good way to make it so my main can see the driver and use it, and my functions file can also see and use driver.我想知道是否有一种好的方法可以让我的 main 可以看到驱动程序并使用它,我的函数文件也可以看到和使用驱动程序。

I have also included pynput because I am thinking maybe the with open statement that gets keyboard presses ( using the escape key to exit the project) is messing with things.我还包括了 pynput ,因为我在想可能导致键盘按下的 with open 语句(使用转义键退出项目)正在搞乱事情。 I do not really understand joining threads and sending info to the queue, but that is for another post.我不太了解加入线程并将信息发送到队列,但那是另一篇文章。 This one is getting my driver to work over multiple files.这个是让我的驱动程序处理多个文件。

Also I know my function names are a mess, I'll get around to learning the proper naming conventions at some point.另外我知道我的 function 名称很乱,我会在某个时候开始学习正确的命名约定。

The loading(listener) is a workaround for until I understand fully how multithreading works.在我完全理解多线程的工作原理之前,加载(侦听器)是一种解决方法。

In my main file I have:在我的主文件中,我有:

import functions as f

def main_Sequence(user_1, listen):
f.loading(listen)
f.sign_in(user_1)
f.loading(listen)
f.accept_Cookies()
f.loading(listen)
driver.refresh()

with keyboard.Listener(on_release=f.on_release) as listener:
    driver = start_Webdriver()
    main_Sequence(user, listener)

In my functions file I have functions like this:在我的函数文件中,我有这样的函数:

def on_release(key):  # TODO FIX Garbage listener BS
    if key == pynput.keyboard.Key.esc:
        return False

def accept_Cookies():
Cookies_box = driver.find_element_by_xpath('//button[contains(., "OK")]')
Cookies_box.click()
return

def start_Webdriver():
    # Using chrome, and maximize browser for fewer issues
    options = webdriver.ChromeOptions()
    options.add_argument("--start-maximized")
    d = webdriver.Chrome(options=options)
    # Open the website
    d.get("URL.com")
    return d

I am wondering how to properly implement this.我想知道如何正确实现这一点。

The error I am getting is:我得到的错误是:

Traceback (most recent call last):
File "*ProjectFolder*/main.py", line 117, in <module> main_Sequence(user, listener)

File "*ProjectFolder*/main.py", line 87, in main_Sequence f.sign_in(user_1)

File "*ProjectFolder*\functions.py", line 117, in sign_in 

alert_Button = driver.find_element_by_xpath("xpath").click()

NameError: name 'driver' is not defined

I have tried everything I could think of, I put it off as long as I did because my initials attempts proved unsuccessful.我已经尝试了所有我能想到的东西,我把它推迟了,因为我最初的尝试被证明是不成功的。

Thanks for the help.谢谢您的帮助。

You can use a singleton pattern, to get the driver object where ever you want it.您可以使用 singleton 模式,在您想要的任何地方获取驱动程序 object。 It would look something like this:它看起来像这样:

class WebDriver:
    __instance__ = None

    def __init__(self):
        if WebDriver.__instance__ is not None:
            raise RuntimeError("Cannot init class twice, as it is as singelton")
        else:
            WebDriver.__instance__ = start_Webdriver()

    @classmethod
    def get_instance(cls):
        """
        :rtype: WebDriver
        """
        if cls.__instance__ is None:
            WebDriver()
        return cls.__instance__

And your code would look like this:您的代码如下所示:

# main.py
with keyboard.Listener(on_release=f.on_release) as listener:
    driver = WebDriver.get_instance()
    main_Sequence(user, listener)


# function.py
def accept_Cookies():
    driver = WebDriver.get_instance()
    Cookies_box = driver.find_element_by_xpath('//button[contains(., "OK")]')
    Cookies_box.click()
    return

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM