导入定义的硒功能浏览器问题

Import defined selenium function browser issue

Set-up

我将 selenium 用于多种用途,发现自己一遍又一遍地定义相同的函数。

我决定在单独的文件中定义函数,并将它们导入到我的工作文件中。


简单示例

如果我在一个文件中定义函数并全部执行,一切正常。见下面简单的full_script.py

# import webdriver
from selenium import webdriver

# create browser
browser = webdriver.Firefox(
        executable_path='/mypath/geckodriver')

# define short xpath function
def el_xp(x):
    return browser.find_element_by_xpath(x)      

# navigate to url
browser.get('https://nos.nl')

# obtain title first article
el_xp('/html/body/main/section[1]/div/ul/li[1]/a/div[2]/h3').text

这成功returns本新闻网站第一篇文章的标题。


问题

现在,当我将脚本拆分为 xpath_function.pyrun_text.py 并保存它们时在我桌面上的 test 文件夹中,一切都不正常。

xpath_function.py

# import webdriver
from selenium import webdriver

# create browser
browser = webdriver.Firefox(
        executable_path='/mypath/geckodriver')

# define short xpath function
def el_xp(x):
    return browser.find_element_by_xpath(x)  

run_test.py

import os
os.chdir('/my/Desktop/test')
import xpath_function as xf

# import webdriver
from selenium import webdriver

# create browser
browser = webdriver.Firefox(
        executable_path='/Users/lucaspanjaard/Documents/RentIndicator/geckodriver')

browser.get('https://nos.nl')

xf.el_xp('/html/body/main/section[1]/div/ul/li[1]/a/div[2]/h3').text

执行run_test.py导致打开2个浏览器,其中一个浏览器导航到新闻网站并出现以下错误,

NoSuchElementException: Unable to locate element: 
/html/body/main/section[1]/div/ul/li[1]/a/div[2]/h3

我想问题是在 xpath_function.pyrun_test.py 中我都定义了一个 browser

但是,如果我没有在 xpath_function.py 中定义浏览器,我会在该文件中收到一个错误,指出没有定义浏览器。

我该如何解决?

您可以通过更改 el_exp 的定义以将浏览器作为额外参数包含在内来轻松修复它:

def el_xp(browser, x):
    return browser.find_element_by_xpath(x)

现在 run_test.py 你可以这样称呼它:

xf.el_xp(browser, '/html/body/main/section[1]/div/ul/li[1]/a/div[2]/h3').text