【问题标题】:Import defined selenium function browser issue导入定义的硒功能浏览器问题
【发布时间】:2018-11-08 10:58:33
【问题描述】:

设置

我将 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

这成功返回了该新闻网站上第一篇文章的标题。


问题

现在,当我将脚本拆分为 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 中定义浏览器,我会在该文件中收到一个错误,即没有定义浏览器。

我该如何解决这个问题?

【问题讨论】:

    标签: python function selenium python-import


    【解决方案1】:

    您可以通过更改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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-23
      • 2019-01-23
      • 1970-01-01
      相关资源
      最近更新 更多