使用 Python Selenium 检查元素是否存在 [英] Checking if element exists with Python Selenium

查看:75
本文介绍了使用 Python Selenium 检查元素是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题 - 我正在使用 selenium (firefox) 网络驱动程序打开一个网页,点击一些链接等,然后截取屏幕截图.

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>

我正在使用 find_element By LINK_TEXT 方法:

I am using the find_element By LINK_TEXT method:

login = driver.find_element(By.LINK_TEXT, "log in").click()

我有点像 Python 菜鸟,所以我有点在与语言作斗争......

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(log in)').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.

我仍然想要一些关于如何检查元素是否存在的指示.此外,隐式/显式等待的示例/解释,而不是使用蹩脚的 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:

  1. 文本更有可能改变;
  2. 如果这对您很重要,您将无法针对本地化版本运行测试.

解决方案:

  1. 您可以使用 xpath 查找具有 ID 或其他某些唯一标识符的父元素或祖先元素,然后找到匹配的子元素/后代元素或;
  2. 您可以为链接本身请求 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 检查元素是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆