首页 > 解决方案 > Python - 处理多处理 Pool.map 中的异常

问题描述

我有以下代码,但是当我尝试它时会引发我什至处理过的那些错误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'

标签: pythonpython-3.xmultiprocessingthreadpool

解决方案


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

推荐阅读