【问题标题】:Returning multiple values with a function使用函数返回多个值
【发布时间】:2019-10-31 15:48:03
【问题描述】:

当我打印时,我得到 4 个代码和 4 个日期,但是当我使用 return 时,我只得到第一个。

这是一个带有 bs4 和 requests 的网页抓取项目。我用正则表达式抓取一个网站。我使用了 containers = soup.find.all(class) 方法来查找包含我要提取的数据的代码块。

def get_codes(containers, pattern):
    for container in containers:
        tweet_bodies = str(container.find('p'))
        shift_codes = re.findall(pattern, tweet_bodies)
        for shift_code in shift_codes:
            str(shift_code)
            return (shift_code)`

def get_date(containers):
    for container in containers:
        tweet_dates = container.find_all('a', class_='tweet-timestamp js-permalink js-nav js-tooltip')
        for date in tweet_dates:
            if 'title' in date.attrs:
                return (date['title'])`

预期:

W9KBJ-95X9T-ZC3KW-BJTJT-5FF3T
CZWJJ-X6XHJ-9CJC5-JTT3J-WZ6WC
KZK3T-K6RSJ-ZWTCK-JTJ3T-T3HJJ
CHCBT-TF6HB-ZC3WC-BT333-KBR3B
13:14 - 28. Okt. 2019
14:30 - 27. Okt. 2019
11:33 - 26. Okt. 2019
15:54 - 25. Okt. 2019`

但我只得到一个日期和一个代码。

【问题讨论】:

  • 你在shift_codesdate.attrs有什么
  • date.attrs:

标签: python function return


【解决方案1】:

return 导致当前函数立即终止*,因此您的 for 循环只会到达第一次迭代。如果您想一直迭代到最后,您可以将您的值累积在一个列表中并在最后返回该列表:

def get_codes(containers, pattern):
    results = []
    for container in containers:
        tweet_bodies = str(container.find('p'))
        shift_codes = re.findall(pattern, tweet_bodies)
        for shift_code in shift_codes:
            results.append(str(shift_code))
    return results

...或者通过将每个return 替换为yield 来将您的函数变成一个生成器。

def get_codes(containers, pattern):
    for container in containers:
        tweet_bodies = str(container.find('p'))
        shift_codes = re.findall(pattern, tweet_bodies)
        for shift_code in shift_codes:
            yield str(shift_code)

(*除非您在 with 块内或带有 finallytry 块内,在这种情况下,可能会在终止之前进行一些清理)

【讨论】:

    【解决方案2】:
     if 'title' in date.attrs:
                    return (date['title'])
    

    您的回报在 if 语句中。 这意味着您的函数可以返回日期,但有时可以返回 None。

    你需要检查为什么 if 语句是 False。

    此外,请确保您的函数始终明确返回您的意思。

    【讨论】:

      猜你喜欢
      • 2020-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-06
      • 2018-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多