如果声明

时间:2015-08-19 09:52:09

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

找不到存在的某些元素我想在if语句中加入:(EDIT)

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
import sys
import smtplib

email = "CampbelltP5wRaX@hotmail.com"
pswd = "EiEHzciBT668"

driver = webdriver.Chrome()
actions = ActionChains(driver)


driver.get("http://www.tumblr.com/login")
driver.find_element_by_id("signup_email").send_keys(email)
driver.find_element_by_id("signup_password").send_keys(pswd)
driver.find_element_by_id("signup_forms_submit").click()

#wait = WebDriverWait(driver, 5)

time.sleep(5)

iframe = driver.find_element_by_tag_name("iframe")
driver.switch_to_frame(iframe)
terminated = driver.find_element_by_xpath("//div[contains(@class, 'center_item')]/h1")



#terminated = driver.find_element_by_xpath("//*[@id='account_actions_suspended']")



if terminated:
    driver.close()

登录失败后,我希望该页面确定该帐户是否被暂停。 html如下:

enter image description here

我想如果我能找到这个元素,我应该能够制作一个if语句。

这是我的错误:(编辑)

Traceback (most recent call last): File "tumblrtest.py", line 32, in <module> terminated = driver.find_element_by_xpath("//div[contains(@class, 'center_item')]/h1") File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 253, in find_element_by_xpath return self.find_element(by=By.XPATH, value=xpath) File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 707, in find_element {'using': by, 'value': value})['value'] File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/webdriver.py", line 196, in execute self.error_handler.check_response(response) File "/Library/Python/2.7/site-packages/selenium/webdriver/remote/errorhandler.py", line 181, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: no such element (Session info: chrome=44.0.2403.155) (Driver info: chromedriver=2.14.313457 (3d645c400edf2e2c500566c9aa096063e707c9cf),platform=Mac OS X 10.7.5 x86_64)

2 个答案:

答案 0 :(得分:0)

试试这个:

var iframe = driver.find_element_by_tag_name("iframe")
driver.switch().frame(iframe)
terminated = driver.find_element_by_Xpath("//div[contains(@class, 'center_item')]/h1")

答案 1 :(得分:0)

你应该抓住NoSuchElementException来检查元素是否存在。如果它存在则暂停。

以下是Java中的示例代码,因为我对Python不熟悉,但我认为您应该理解它:)

try {
  WebElement terminated = driver.findElement(By.xpath("//div[contains(@class, 'center_item')]/h1"));
} catch (NoSuchElementException e) {
  System.out.println("The user is not suspended");
}

如果这个错误消息出现在iframe中,或者被ajax加载,那么你应该在我的示例代码之前处理这些问题(切换到iframe;显式或隐式等待;等等......)