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

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

我想验证一个元素并检查它是否存在。我尝试了很多代码,但都出现错误。我已经尝试过“if driver.find ...”,但出现错误。有什么方法可以验证元素没有错误吗?我用了 Selenium 。

我已经尝试过这个:

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("")

最佳答案

可以通过检查WebElementslistsize来实现,如果size大于0则表示该元素存在于页面上,否则不存在。
你的代码应该是这样的:

if len(driver.find_elements_by_xpath("//input[@name='username']"))>0:
    # Element is present
    print("Alert")
else:
    # Element is not present
    print ("Nothing")

关于python - 检查元素是否存在,如果不存在则执行 ..,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56934063/

相关文章:

python-3.x - 在networkx中设置自定义节点相等性比较

testing - 使用 Junit/Test NG 在 Selenium 中以编程方式(不使用 ANT)创建测试报告

java - 将执行测试所需的时间附加到最终用户友好的 .xls/.csv 文件中

python - scipy.optimize.minimize 忽略约束

Python,用短破折号代替长破折号?

python - 导入错误 : cannot import name 'load_entry_point' (PIP)

python - 为什么我需要 'b' 来使用 Base64 对字符串进行编码?

python - Python 列表中的交替方向 - 更多 Pythonic 解决方案

python - 无法打印代码的第一个和最后一个字符

selenium - WebDriver:如何自动输入屏蔽生日(//)字段