检查元素是否存在,如果不存在则执行..

时间:2019-07-08 11:35:12

标签: python python-3.x selenium selenium-webdriver

我想验证一个元素并检查它是否存在。我尝试了许多代码,但都出错了。我已经尝试过使用“ if driver.find ...”,但是出现错误。有没有办法验证元素没有错误?我用硒。

我已经尝试过了:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException

driver = webdriver.Firefox()
driver.get("https://www.instagram.com/accounts/login/")

def check_exists_by_xpath(xpath):
    try:
        webdriver.find_element_by_xpath("//input[@name='username']")
        print ("Alert")
        raw_input("")
    except NoSuchElementException:
        print ("Nothing")
        raw_input("")

我知道了:

>>> from selenium import webdriver
>>> from selenium.webdriver.common.keys import Keys
>>> from selenium.common.exceptions import NoSuchElementException
>>>
>>> driver = webdriver.Firefox()
>>> driver.get("https://www.instagram.com/accounts/login/")
>>>
>>> def check_exists_by_xpath(xpath):
...     try:
...         webdriver.find_element_by_xpath("//input[@name='username']")
... print ("Alert")
  File "<stdin>", line 4
    print ("Alert")
    ^
IndentationError: unexpected unindent
>>> raw_input("")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'raw_input' is not defined
>>>     except NoSuchElementException:
  File "<stdin>", line 1
    except NoSuchElementException:
    ^
IndentationError: unexpected indent
>>>         print ("Nothing")
  File "<stdin>", line 1
    print ("Nothing")
    ^
IndentationError: unexpected indent
>>> raw_input("")

1 个答案:

答案 0 :(得分:0)

您可以通过检查size的{​​{1}}中的list来实现,如果大小大于0,则表示该元素存在于页面上,否则不存在礼物。
您的代码应类似于:

WebElements
相关问题