验证元素存在硒 [英] verify element existence selenium

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

问题描述

我知道之前在某些迭代中已经问过这个问题.但即使在查看 API 之后,我也无法弄清楚如何做到这一点.

我想通过网络抓取数据,我有以下代码:

browser = webdriver.Firefox()browser.get(url)browser.find_element_by_xpath('//path')

现在在 find_element 部分执行之前.我想知道该元素是否确实存在.我尝试了以下方法:

尝试:browser.find_element_by_xpath('//path')除了 NoSuchElementException:打印('失败')

if (browser.find_element_by_xpath('//path')[0].size() == 0):打印('失败')

但它们都不起作用,即使 API 说 size() 是 WebElement 的可调用函数,并且异常由 find 方法系列抛出.我不明白为什么这些都不起作用.但如果有人能给我一个解释和一个有效的例子,我将不胜感激.

解决方案

如果元素丢失,您的第一个代码片段应该引发 NoSuchElementException.如果它没有这样做,那么从您问题中的信息中不清楚为什么会这样.(或者也许你期望它找不到一个元素,但它确实找到一个?)

第二个代码段无法工作,因为 find_element_... 方法返回 WebElement 对象,而不是对象列表.你必须这样做:

if len(browser.find_elements_by_xpath('//path')) == 0:打印('失败')

注意复数 find_elements_... 查找复数列表中元素的函数,如果它们没有找到任何东西,则列表长度为零.

顺便说一下,WebElement 对象上的 size() 方法返回元素的渲染大小,即它在页面上的高度和宽度.>

I know that this question has been asked in some iteration before. But I can't figure out how to do this even after looking at the API.

I want to scrape data over the web and I have the following code:

browser = webdriver.Firefox()
browser.get(url)
browser.find_element_by_xpath('//path')

Now before the find_element part executes. I want to know if the element in fact exists. I've tried the following:

try:
    browser.find_element_by_xpath('//path')
except NoSuchElementException:
    print ('failure')

AND

if (browser.find_element_by_xpath('//path')[0].size() == 0):
    print ('failure')

But neither of them work, even though the API says size() is a callable function of WebElement and the exception is throw by the find family of methods. I don't understand why neither of those work. But if anyone could give me an explanation and a working example I would greatly appreciate it.

解决方案

Your first code snippet should raise NoSuchElementException if the element is missing. If it does not do that, then it is unclear from the information in your question why that's the case. (Or maybe you expect it to not find an element but it does find one?)

The 2nd snippet cannot work because the find_element_... methods return WebElement objects, not lists of objects. You'd have to do:

if len(browser.find_elements_by_xpath('//path')) == 0:
    print ('failure')

Note the plural find_elements_... The functions to find elements that are in the plural return lists, and if they don't find anything the list is of length zero.

By the way, the size() method on WebElement objects returns the rendered size of the element, that is, its height and width on the page.

这篇关于验证元素存在硒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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