【问题标题】:Is there a more elegant way to handle empty values in this scraper?有没有更优雅的方法来处理这个刮板中的空值?
【发布时间】:2012-11-25 17:09:47
【问题描述】:

现在我已经找到了How do I strtotime in python?,我想知道是否有更优雅的方法来处理日期为空的条目,如果我尝试 strptime() 它们会返回错误。

warrant_issued = cells[4].get_text().strip()
try:
    warrant_issued_no = datetime.strptime(warrant_issued, '%m/%d/%Y')
except:
    warrant_issued_no = ''

这行得通,但我在每行中解析四到五个日期,这似乎既冗长又重复。我在想我应该定义一个函数,但还有其他方法可以让这个函数更 Python 吗?

为简洁起见,我一开始就使用了from datetime import datetime,所以datetime.strptime() 有效。否则我需要datetime.datetime.strptime()

【问题讨论】:

    标签: python datetime coding-style strptime pep


    【解决方案1】:

    我认为定义一个函数并只捕获你知道如何处理的异常正是这样做的方法。

    def parse_datetime(warrant_issued):
       try:
          warrant_issued_no = datetime.strptime(warrant_issued, '%m/%d/%Y')
       except ValueError:
          warrant_issued_no = ''
    
    warrants_issued = [ parse_datetime(cell.get_text().strip()) for cell in cells ]
    

    【讨论】:

    • 这有一个小缺点,所有无效的日期字符串都被“忽略”,而jdotjdot的解决方案只忽略空字符串。这可能是也可能不是 OP 想要的。
    • @Bakuriu 我实际上已经记录了异常,所以我可以检查它们并确保我没有错过我需要捕捉的日期。
    【解决方案2】:

    我认为你可能会更好地做一些类似于 @mgilson 所说的事情,但使用if 语句而不是try/catch,因为你可能会意外发现你没有发现的错误意思是。

    我的理解是,您要在此处捕获的错误是日期字段为空白时,所以这就是我要处理的问题。

    def parse_datetime(warrant_issued):
        # Using Python's "truthiness" to take care of both '' and None, however it comes out
        if warrant_issued:
            warrant_issued_no = datetime.strptime(warrant_issued, '%m/%d/%Y')
        else:
            warrant_issued_no = ''
    
    warrants_issued = [parse_datetime(cell.get_text().strip()) for cell in cells]
    

    这样,如果您最终得到一些其他错误,仍然会引发 ValueError 但不是从那里没有日期,它会引发异常,您将能够处理它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多