【问题标题】:Python - Handle Exception inside multiprocessing Pool.mapPython - 处理多处理 Pool.map 中的异常
【发布时间】:2019-12-11 06:00:21
【问题描述】:

我有以下代码,但是当我尝试它时会引发那些我什至用try except 处理的错误

from multiprocessing.dummy import Pool as ThreadPool 
def getPrice(product='',listing=False):
    try:
        avail = soup.find('div',id='availability').get_text().strip()
    except:
        avail = soup.find('span',id='availability').get_text().strip()

pool.map(getPrice, list_of_hashes)

它给了我以下错误

Traceback (most recent call last):
  File "C:\Users\Anonymous\Desktop\Project\google spreadsheet\project.py", line 4, in getPrice
    avail = soup.find('div',id='availability').get_text().strip()
AttributeError: 'NoneType' object has no attribute 'get_text'

【问题讨论】:

  • avail = soup.find('span',id='availability').get_text().strip()except 语句中,所以它不在你的函数中处理

标签: python python-3.x multiprocessing threadpool


【解决方案1】:

avail = soup.find('span',id='availability').get_text().strip()except 语句中,所以它不在你的函数中处理

更好地循环属性,如果找不到则返回默认值:

def getPrice(product='',listing=False):
    for p in ['div','span']:
      try:
         # maybe just checking for not None would be enough
         avail = soup.find(p,id='availability').get_text().strip()
         # if no exception, break
         break
      except Exception:
        pass
    else:
        # for loop ended without break: no value worked
        avail = ""
    # don't forget to return your value...
    return avail

【讨论】:

    猜你喜欢
    • 2019-01-30
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2015-01-12
    • 1970-01-01
    • 2013-10-02
    • 2017-04-02
    • 2018-04-03
    相关资源
    最近更新 更多