缩短 Python 异常处理的表达式

Shorten expression for Python exceptions handling

我正在使用 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()

你似乎有 3 个不同的选项 xpath_issuer 所以你遍历了所有这些。然后你设置 find_issuer。之后你用 issuer 做一些事情。

也许你可以尝试让 issuer return 一些东西,如果找到东西,它会指示。如果您传递 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()