如何将XPath置于可选模式

时间:2019-03-03 11:55:44

标签: python selenium xpath

此XPath可能会在某个时间或某些时间不可用。

如果拒绝为真,那么我正在使用if语句:

from selenium import webdriver
from selenium.webdriver.support.select import Select
from selenium.webdriver.firefox.options import Options
import time

import bs4
import requests
url="abc"

options = Options()
options.set_preference("dom.webnotifications.enabled", False)

driver=webdriver.Firefox(executable_path="C:\driver\geckodriver.exe",options=options)
driver.get(url)
driver.maximize_window()

reject = driver.find_element_by_xpath("/html/body/div/div/div/main/div/section/div[2]/div[2]/div/ul/a[1]/div[3]/label")
if reject:
    driver.find_element_by_xpath("/html/body/div[1]/div/div/main/div/section/div[2]/div[2]/div/ul/a[1]/div[1]/span/i").click()
    time.sleep(1)
    driver.find_element_by_xpath("/html/body/div[1]/div/div/main/div/section/div[2]/div[2]/div/ul/a[1]/div[1]/div/ul/li[2]").click()
    time.sleep(2)
    driver.find_element_by_xpath("/html/body/div[3]/div/div/div[3]/button[1]").click()
    time.sleep(5)

# Above code blocking to run below code (if reject is None).

neighbourhood= Select(driver.find_element_by_name("Locality"))
neighbourhood.select_by_value("5001641")

但是问题在于此拒绝变量XPath是否不存在,因此在代码下方显示了错误并被阻止。

如果XPath可用,如何使此拒绝变量为可选,如果不可用,则工作,然后保留它并运行以下代码。

2 个答案:

答案 0 :(得分:2)

您可以捕获到异常。如下所示:

...
try:
    reject = driver.find_element_by_xpath("/html/body/div/div/div/main/div/section/div[2]/div[2]/div/ul/a[1]/div[3]/label")
except:
    print("No element found")

if reject:
...

如果您更需要此功能,则可以为此创建一个实用程序方法。

def elementVisible(xpath):
    try:
        driver.find_element_by_xpath(xpath);
        return true;
    except:
        return false;

答案 1 :(得分:0)

try-except 块可以解决问题。

try:
  reject = driver.find_element_by_xpath("/html/body/div/div/div/main/div/section/div[2]/div[2]/div/ul/a[1]/div[3]/label")
except:
  print("An exception occurred")

每当未找到xpath时,都会执行print语句,然后执行其他代码而不会像以前一样出错。