我构建了一个测试来检查元素是否可见,我的问题是有时测试有效,有时无效。我在代码中没有id定位器,所以我使用了我的另一个定位器(Xpath,CSS选择器(。你知道问题是因为我没有id定位器吗?或者我可能需要使用不同的方法来通过可见性定位元素谢谢这是我的代码:
free = driver.find_element(By.XPATH, "/html//div[@id='root']/div[1]/div[1]//div[")
if free.is_displayed():
print("google data found")
else:
print("google data not found")
time.sleep(1)
payable = driver.find_element(By.CSS_SELECTOR,".ItemCard__StyledCard-sc-1fl623o-3.MuiCard-root.MuiPaper")
if payable.is_displayed():
print("found payable attractions")
else:
print("not found payable attractions")
time.sleep(3)
我想您应该使用预期条件可见性显式等待,而不是is_displayed()
。类似以下内容:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 20)
try:
wait.until(EC.visibility_of_element_located((By.XPATH, "/html//div[@id='root']/div[1]/div[1]//div")))
print("google data found")
except:
print("google data not found")
time.sleep(1)
try:
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".ItemCard__StyledCard-sc-1fl623o-3.MuiCard-root.MuiPaper")))
print("found payable attractions")
except:
print("not found payable attractions")
此外,XPath定位器也不好。其末尾的[
使其成为无效定位器。