我正在使用try / except来检查xpath替代来源,以输入网站变量。

它必须执行多次,所以我正在寻找一种缩短表达式的方法。也许可以以某种方式使用上下文管理器?

在此示例中,我正在检查变量issuername的两个替代xpath源。

try:
    xpath_issuer = ".//*[@id='dv_PRE88f496c28ad6488895f1ffc383fae8bd_list_list']/div/div[3]/table/tbody/tr[2]/td[2]"
    find_issuer = driver.find_element_by_xpath(xpath_issuer)
    issuer = re.search(r"(.+)", find_issuer.text).group()
except NoSuchElementException:
    pass
try:
    xpath_issuer = ".//*[@id='dv_PRE00e883469a264528b20fbbc31b0da4a2_list_list']/div/div[3]/table/tbody/tr[1]/td[2]/a"
    find_issuer = driver.find_element_by_xpath(xpath_issuer)
    issuer = re.search(r"(.+)", find_issuer.text).group()
except NoSuchElementException:
    pass
try:
    xpath_name = ".//*[@id='cols']/div[1]/div[1]/h1"
    find_name = driver.find_element_by_xpath(xpath_name)
    name = re.search(r"(.+)", find_name.text).group()
except NoSuchElementException:
    pass

最佳答案

这个怎么样:

listXPath = [".//*[@id='dv_PRE88f496c28ad6488895f1ffc383fae8bd_list_list']/div/div[3]/table/tbody/tr[2]/td[2]", ".//*[@id='dv_PRE00e883469a264528b20fbbc31b0da4a2_list_list']/div/div[3]/table/tbody/tr[1]/td[2]/a", ".//*[@id='cols']/div[1]/div[1]/h1"]
class Work():
    def __init__(self):
        self.getIssuer()

    def getIssuer(self):
        for i in range(len(listXPath)):
            xPath = listXPath[i]
            try:
                find_issuer = driver.find_element_by_xpath(xpath_issuer)
                issuer = re.search(r"(.+)", find_issuer.text).group()
            except:
                pass

# Run clas
Work()


您似乎对xpath_issuer有3个不同的选项,因此可以遍历所有这些选项。然后设置find_issuer。之后,您可以使用issuer进行操作。

也许您可以尝试让issuer返回一些表明是否找到了东西的东西。如果您通过issuer显然有效,则执行return语句。

例如:

listXPath = [".//*[@id='dv_PRE88f496c28ad6488895f1ffc383fae8bd_list_list']/div/div[3]/table/tbody/tr[2]/td[2]", ".//*[@id='dv_PRE00e883469a264528b20fbbc31b0da4a2_list_list']/div/div[3]/table/tbody/tr[1]/td[2]/a", ".//*[@id='cols']/div[1]/div[1]/h1"]
class Work():
    def __init__(self):
        x = self.getIssuer()
        print(x)

    def getIssuer(self):
        for i in range(len(listXPath)):
            xPath = listXPath[i]
            try:
                find_issuer = driver.find_element_by_xpath(xpath_issuer)
                issuer = re.search(r"(.+)", find_issuer.text).group()
                return 'DoneIt'
            except:
                pass

# Run clas
Work()

关于python-2.7 - 缩短用于Python异常处理的表达式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30650122/

10-12 05:54