【发布时间】: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.py 和 run_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.py 和run_test.py 中我都定义了browser。
但是,如果我没有在 xpath_function.py 中定义浏览器,我会在该文件中收到一个错误,即没有定义浏览器。
我该如何解决这个问题?
【问题讨论】:
标签: python function selenium python-import