【问题标题】:Code completes error free but print function not working代码完成无错误但打印功能不起作用
【发布时间】:2018-11-05 21:23:23
【问题描述】:

我正在尝试学习 python,并且一直在关注 youtube 上的教程。到目前为止进展顺利,但如果我运行代码,它会毫无错误地完成,但它不会打印我想要的东西。我完全复制了教程中的内容,但找不到差异。只是对为什么它可以完成代码但不能打印(代码)感到困惑。任何帮助都会很棒,我觉得这可能是一个我忽略的简单修复。

干杯,

import bs4 as bs
import pickle
import requests

def save_sp500_tickers():
    resp = requests.get('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')
    soup = bs.BeautifulSoup(resp.text, "lxml")
    table = soup.find('table',{'class': 'wikitable sortable'})
    tickers = []
    for row in table.findALL('tr')[1:]:
        ticker = row.findALL('td')[0].text
        tickers.append(ticker)

    with open("sp500tickers.pickle","wb") as f:
        pickle.dump(tickers, f)

    print(tickers)

    return tickers

    save_sp500_tickers()

【问题讨论】:

  • 如果您的数组是空的,那么print() 将不打印任何内容(因此请确保它不是)。而且您的函数save_sp500_tickets() 调用也在其内部。
  • save_sp50_tickers() 大概不应该在函数定义中:它应该被取消缩进

标签: python printing beautifulsoup pickle


【解决方案1】:

save_sp500_tickers() 调用缩进错误,因此它是函数定义的一部分,不会被执行。

【讨论】:

    【解决方案2】:

    谢谢大家。删除 save_sp500_tickers() 的缩进有效。 我也不得不摆脱

    for row in table.findALL('tr')[1:]:
        ticker = row.findALL('td')[0].text
    

    把它变成

    for row in table.find_all('tr')[1:]:
        ticker = row.find_all('td')[0].text
    

    原来 BeautifulSoup 在更新的版本中改变了它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-20
      • 2021-12-17
      • 1970-01-01
      • 2020-08-29
      • 2018-08-06
      • 1970-01-01
      • 1970-01-01
      • 2019-05-26
      相关资源
      最近更新 更多