检查Python Selenium是否存在元素

编程入门 行业动态 更新时间:2024-10-27 14:31:55
本文介绍了检查Python Selenium是否存在元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我遇到问题-我正在使用硒(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可以判断元素是否存在,可以在此处找到很好的等待示例: seleniumhq/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: seleniumhq/docs/04_webdriver_advanced.html

    更多推荐

    检查Python Selenium是否存在元素

    本文发布于:2023-11-27 15:44:19,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1638615.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:是否存在   元素   Python   Selenium

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!