如何将 XPath 置于可选模式 [英] How to put XPath into optional mode

查看:20
本文介绍了如何将 XPath 置于可选模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此 XPath 有时可用,有时不可用.

This XPath may available sometime or sometime not.

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

If reject is true then I am using if statement:

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 可用,如何使此拒绝变量可选,然后工作,如果不可用,则保留它 &运行下面的代码.

how to make this reject variable optional if XPath available then work if not then leave it & run below code.

推荐答案

您可以捕获异常.类似于以下内容:

You could catch the exception. Something like following:

...
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:
...

如果你更频繁地需要这个,你可以为此创建一个实用方法.

If you need this more often you could create a utility method for that.

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

这篇关于如何将 XPath 置于可选模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆