我想验证一个元素并检查它是否存在。我尝试了很多代码,但都出现错误。我已经尝试过“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("")
最佳答案
可以通过检查WebElements
的list
的size
来实现,如果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/