Python中如何使用Selenium判断当前元素是否处于可见状态

我用的 selenium,然后通过 find_elements_by_css_selector 方法找到多个相同元素(但实际只显示了一个),我就想找到显示的那一个,本人刚接触 python 没几天,还望大神指教,谢谢!


Python中如何使用Selenium判断当前元素是否处于可见状态
3 回复

在Selenium里判断元素是否可见,直接用is_displayed()方法就行。这方法返回TrueFalse,能直接用在条件判断里。

不过要注意,is_displayed()检查的是元素在页面上的视觉状态,比如CSS的display: none或者visibility: hidden。如果元素压根没在DOM里,你得先用find_element定位,不然会抛NoSuchElementException

这里有个完整的例子,演示了怎么用:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException

# 启动浏览器
driver = webdriver.Chrome()
driver.get("https://example.com")

try:
    # 先找到元素
    element = driver.find_element(By.ID, "some-element-id")
    
    # 判断是否可见
    if element.is_displayed():
        print("元素当前是可见的。")
    else:
        print("元素当前不可见(可能被隐藏)。")
        
except NoSuchElementException:
    print("在页面上没找到这个元素。")
finally:
    driver.quit()

简单说就是:先定位,再调用is_displayed()判断。


试试这个
https://stackoverflow.com/questions/15937966/in-python-selenium-how-does-one-find-the-visibility-of-an-element

from selenium import webdriver

driver = webdriver.Firefox()
driver.get(‘http://www.google.com’)
element = driver.find_element_by_id(‘gbqfba’) #this element is visible
if element.is_displayed():
print "Element found"
else:
print "Element not found"

hidden_element = driver.find_element_by_name(‘oq’) #this one is not
if hidden_element.is_displayed():
print "Element found"
else:
print “Element not found”

谢谢!

回到顶部