如果找不到xpath,如何关闭当前驱动程序选项卡?

时间:2019-04-20 01:40:57

标签: python selenium google-chrome

如果不存在特定的XPath,则需要python来关闭选项卡。我该怎么办?

我在Chrome中使用Python + Selenium。

from selenium import webdriver
import os
import time
import pyautogui
option = webdriver.ChromeOptions()
chrome_prefs = {}
option.experimental_options["prefs"] = chrome_prefs
chrome_prefs["profile.default_content_settings"] = {"images": 2}
chrome_prefs["profile.managed_default_content_settings"] = {"images": 2}
chrome_prefs["profile.default_content_settings"] = { "popups": 2 }
option.add_argument("--disable-notifications")


driver = webdriver.Chrome(chrome_options=option)
driver.get('https://www.spiritfanfiction.com/login')
driver.find_element_by_xpath("//*[@id='Usuario']").send_keys("my username")
driver.find_element_by_xpath("//*[@title='Senha']").send_keys("y password")
driver.find_element_by_xpath("//*[@class='btn btn-primary']").send_keys("my password")
driver.find_element_by_xpath("//*[@class='btn btn-primary']").click()
LinkDoPerfil = driver.get('https://www.spiritfanfiction.com/perfil/bestofgguk')

try:
        driver.find_element_by_xpath('//*[@class="fa fa-eye"]').click()
else:
        driver.close()

如果没有找到,这是我需要关闭的行:

driver.find_element_by_xpath('//*[@class="fa fa-eye"]').click()

3 个答案:

答案 0 :(得分:0)

from selenium import webdriver

driver = webdriver.Chrome()
driver.get("https://www.google.com")

def checkExistElement(elementId):
    try:
        driver.find_element_by_id(elementId)
        return True
    except: print('Cannot find')
    return False

if(not checkExistElement('testID')):
    print('Close Tab')
    driver.close()


# Other Operation
# ...

答案 1 :(得分:0)

您可以尝试find_elements_by_查找元素。这样,您可以避免等待异常发生。

尝试一下:

elements = driver.find_elements_by_xpath('//*[@class="fa fa-eye"]')
if len(elements) > 0:
    elements.pop(0).click()
else:
    ActionChains(driver).key_down(Keys.CONTROL).send_keys('w').key_up(Keys.CONTROL)

答案 2 :(得分:0)

NoSuchElementException找不到元素时,会引发异常(try: driver.find_element_by_xpath('//*[@class="fa fa-eye"]') except NoSuchElementException: driver.close() )。使用它来确定是否应关闭窗口。

e.Graphics