除块外重复尝试的替代方法

2024-04-25 22:55:20 发布

您现在位置:Python中文网/ 问答频道 /正文

在我编写的一个脚本中,有一段代码如下所示:

try:
  prize = row.find_element(By.XPATH, './div[contains(@class, "divCell")][3]').text
except:
  prize = ''
try:
  field = row.find_element(By.XPATH, './div[contains(@class, "divCell")][4]').text
except:
  field = ''
try:
  country = row.find_element(By.XPATH, './div[contains(@class, "divCell")][5]/span[1]/a').get_attribute('title')
except:
  country = ''
try:
  city = row.find_element(By.XPATH, './div[contains(@class, "divCell")][5]/span[2]').text
except:
  city = ''
try:
  winner = row.find_element(By.XPATH, './div[contains(@class, "divCell")][6]/span[2]/span').get_attribute('data-highlightingclass')
except:
  winner = ''
try:
  runnerup = row.find_element(By.XPATH, './div[contains(@class, "divCell")][7]/span[2]/span').get_attribute('data-highlightingclass')
except:
  runnerup = ''

我是Python新手,想知道是否有其他更简洁的方法来实现这一点?你知道吗


Tags: textdivgetbyattributeelementfindxpath
1条回答
网友
1楼 · 发布于 2024-04-25 22:55:20

前言:请提供Minimal, Complete, and Verifiable example帮助我们。你知道吗

我假设你正在使用硒。你知道吗


你有不同的选择。你知道吗

一句话就可以把他们全部抓住

如果所有元素都是必需的,那么您最好使用一个更大的try-catch:

try:
    prize = row.find_element_by_xpath('./div[contains(@class, "divCell")][3]').text
    field = row.find_element_by_xpath('./div[contains(@class, "divCell")][4]').text
    country = row.find_element_by_xpath('./div[contains(@class, "divCell")][5]/span[1]/a').get_attribute('title')
    ...
except NoSuchElementException:
    # Do something smart

(请注意,Selenium文档recommends to使用方法WebDriver.find_element_by_xpath,而不是直接使用WebDriver.find_element

封装

(由@vks推荐)

您可以环绕异常并返回None,而不是使用可以直接引发异常的方法:

def find_element_by_xpath_or_None(haystack, xpath):
    try:
        return haystack.find_element_by_xpath(xpath)
    except NoSuchElementException:
        return None

然后这样使用:

prize = find_element_by_xpath_or_None(row, './div[contains(@class, "divCell")][3]')
prize = prize.text if prize else ''

field = find_element_by_xpath_or_None(row, './div[contains(@class, "divCell")][4]')
field = prize.text if prize else ''

country = find_element_by_xpath_or_None(row, './div[contains(@class, "divCell")][5]/span[1]/a')
country = country.get_attribute('title') if country else ''

编辑:也可以使用lambdas。你知道吗

完全封装

您甚至可以通过使用lambdas显式地声明要提取的内容来实现精简:

def find_element_by_xpath_or_None(haystack, xpath, access_fun):
    try:
        return access_fun(haystack.find_element_by_xpath(xpath))
    except NoSuchElementException:
        return None

以及:

field = find_element_by_xpath_or_None(
    row, './div[contains(@class, "divCell")][4]',
    lambda e: e.text
) or ''

country = find_element_by_xpath_or_None(
    row, './div[contains(@class, "divCell")][5]/span[1]/a',
    lambda e: e.get_attribute('title')
) or ''

相关问题 更多 >