【发布时间】:2019-05-02 11:32:29
【问题描述】:
我正在尝试将我的脚本分成不同的函数(因此更容易重复使用部分)但是当我这样做时,selenium 似乎无法找到 css 选择器。
文件夹结构:
- Startup.py
- Webdriver 文件夹
- 包含 init.py
- 和 login.py
startup.py
from selenium import webdriver
from webtesting import login
def browser(usernamefield, passwordfield, loginbutton):
print 'Starting up Firefox'
browser = webdriver.Firefox()
print 'browsing to websiteadress'
browser.get('websiteadress')
login.loginsteps(usernamefield, passwordfield, loginbutton)
usernamefield = '#login-username'
passwordfield = 'input.input-default:nth-child(5)'
loginbutton = '.button'
if __name__=='__main__':
browser(usernamefield,passwordfield,loginbutton)
login.py
def loginsteps(usernamefield, passwordfield, loginbutton):
try:
userlogin = browser.find_element_by_css_selector(usernamefield)
print 'found <%s> element with that class name!' % (userlogin)
except:
print 'Was not able to find an element <%s> with that name.' % (usernamefield)
try:
userpass = browser.find_element_by_css_selector(passwordfield)
print 'found <%s> element with that class name!' % (userpass)
except:
print 'Was not able to find an element <%s> with that name.' % (passwordfield)
try:
logincss = browser.find_element_by_css_selector(loginbutton)
print 'found <%s> element with that class name!' % (logincss)
except:
print 'Was not able to click login.'
except:
print 'Was not able to find login element.'
现在,如果我运行它,浏览器会启动,但我在 css 选择器上遇到异常,因此它无法在浏览器会话中正确运行第二个函数。
在终端打印:
- 启动 Firefox
- 浏览到网站地址
- 找不到具有该名称的元素 。
- 找不到元素 用那个名字。
- 找不到登录元素。
但是,当我在一个函数中测试运行它时,它确实可以工作。
from selenium import webdriver
def browser(usernamefield, passwordfield, loginbutton):
print 'Starting up Firefox'
browser = webdriver.Firefox()
print 'browsing to website'
browser.get('webadress')
#login.loginsteps(usernamefield, passwordfield, loginbutton)
try:
userlogin = browser.find_element_by_css_selector(usernamefield)
print 'found usernamefield element with that class name!'
except:
print 'Was not able to find an element <%s> with that name.' % (usernamefield)
try:
userpass = browser.find_element_by_css_selector(passwordfield)
print 'found userpass element with that class name!'
except:
print 'Was not able to find an element <%s> with that name.' % (passwordfield)
try:
logincss = browser.find_element_by_css_selector(loginbutton)
print 'found loginbutton element with that class name!'
except:
print 'Was not able to find login element.'
usernamefield = '#login-username'
passwordfield = 'input.input-default:nth-child(5)'
loginbutton = '.button'
if __name__=='__main__':
startup.browser(usernamefield,passwordfield,loginbutton)
这个返回值确实有效,但是在这个场景中,我无法从这个脚本的各个部分创建单独的函数,把它变成一个大意大利面。
- 启动 Firefox
- 浏览网站
- 找到具有该类名称的 usernamefield 元素!
- 找到具有该类名称的 userpass 元素!
- 找到具有该类名的 loginbutton 元素!
如何使 python selenium 与单独的函数一起工作? 就像在当前设置中一样,我将不得不复制我的脚本而不是能够重用代码....
【问题讨论】:
标签: css python-2.7 selenium firefox