问题描述
我遇到问题-我正在使用硒(firefox)Web驱动程序打开网页,单击一些链接等,然后捕获屏幕截图.
I have a problem - I am using the selenium (firefox) web driver to open a webpage, click a few links etc. then capture a screenshot.
我的脚本可以从CLI正常运行,但是通过cronjob运行时,它并没有通过第一个find_element()测试.我需要添加一些调试程序,或一些帮助我弄清其失败原因的东西.
My script runs fine from the CLI, but when run via a cronjob it is not getting past the first find_element() test. I need to add some debug, or something to help me figure out why it is failing.
基本上,我必须先单击登录"锚点,然后才能进入登录页面.元素的构造为:
Basically, I have to click a 'log in' anchor before going to the login page. The construct of the element is:
<a class="lnk" rel="nofollow" href="/login.jsp?destination=/secure/Dash.jspa">log in</a>
我正在通过LINK_TEXT方法使用find_element:
I am using the find_element By LINK_TEXT method:
login = driver.find_element(By.LINK_TEXT, "log in").click()
我有点像Python Noob,所以我在和这种语言作斗争...
I am a bit of a Python Noob, so I am battling with the language a bit...
A)我如何检查链接是否已被python实际拾取?我应该使用try/catch块吗?
A) How do I check that the link is actually being picked up by python? Should I use try/catch block?
B)是否有比LINK_TEXT更好/更可靠的方法来定位DOM元素?例如.在JQuery中,可以使用更具体的选择器$('a.lnk:contains(login)').do_something();
B) Is there a better/more reliable way to locate the DOM element than by LINK_TEXT? E.g. In JQuery, you can use a more specific selector $('a.lnk:contains(log in)').do_something();
我已经解决了主要问题,这只是手指上的麻烦-我在调用脚本时使用了错误的参数-简单的错误.
I have solved the main problem and it was just finger trouble - I was calling the script with incorrect parameters - Simple mistake.
我仍然希望找到一些有关如何检查元素是否存在的指针.同样,使用隐式/显式Waits的示例/解释,而不是使用糟糕的time.sleep()调用.
I'd still like some pointers on how to check whether an element exists. Also, an example/explanation of implicit / explicit Waits instead of using a crappy time.sleep() call.
干杯,ns
推荐答案
A)是.检查元素是否存在的最简单方法是在try/catch
内简单地调用find_element
.
A) Yes. The easiest way to check if an element exists is to simply call find_element
inside a try/catch
.
B)是的,出于两个原因,我总是尝试不使用元素文本来标识元素:
B) Yes, I always try to identify elements without using their text for 2 reasons:
- 文本更容易更改,并且
- 如果这对您很重要,您将无法对本地化版本进行测试.
解决方案之一:
- 您可以使用xpath查找具有ID或其他唯一标识符的父元素或祖先元素,然后找到与或相匹配的子代/后代.
- 您可以请求链接本身的ID或名称或其他唯一标识符.
对于后续问题,使用try/catch
可以判断元素是否存在,可以在此处找到很好的等待示例: http://seleniumhq.org/docs/04_webdriver_advanced.html
For the follow up questions, using try/catch
is how you can tell if an element exists or not and good examples of waits can be found here: http://seleniumhq.org/docs/04_webdriver_advanced.html
这篇关于检查Python Selenium是否存在元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!