【问题标题】:Python TypeError: slice indices must be integers or None or have an __index__ methodPython TypeError:切片索引必须是整数或无或具有 __index__ 方法
【发布时间】:2020-07-01 12:47:47
【问题描述】:

我正在尝试提取一些数据,我有一个函数可以在我返回后获取数组中的所有标签。

我的代码:

def getfontCats(soup):
    cats_name = soup.find("div", {"class": ["fontTagsMain"]}).find_all("a")
    cat_list = []
    for cats in cats_name:
        cat_list.append(cats.get_text())

    return cat_list


for sk in set(getListing(soup)):
    print(sk)
    print(getfontCats(sk))
    print("###################################################")
    time.sleep(1)

HTML 内容(汤):

<div class="fontTagsMain">
<a href="/animal-fonts.php" class="fontTag">Animal</a><a href="/comic-cartoon-fonts.php" class="fontTag">Comic Cartoon</a><a href="/cartoon-fonts.php" class="fontTag">Cartoon</a><a href="/comic-fonts.php" class="fontTag">Comic</a><a href="/fun-fonts.php" class="fontTag">Fun</a><a href="/funny-fonts.php" class="fontTag">Funny</a><a href="/comic-book-fonts.php" class="fontTag">Comic Book</a> </div>

输出:

Traceback (most recent call last):
  File "/Users/evilslab/Documents/Websites/www.futurepoint.dev.cc/dobuyme/socket/fonts.py", line 109, in <module>
    print(getfontCats(sk))
  File "/Users/evilslab/Documents/Websites/www.futurepoint.dev.cc/dobuyme/socket/fonts.py", line 40, in getfontCats
    cats_name = soup.find("div", {"class": ["fontTagsMain"]}).find_all("a")
TypeError: slice indices must be integers or None or have an __index__ method

但是当我使用我在外部函数内部使用的代码时它可以工作。但是当我尝试用函数调用代码时,它给了我错误。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    是的,已修复。对不起,我在函数中初始化了汤

    【讨论】:

      猜你喜欢
      • 2018-06-06
      • 2017-07-27
      • 2015-04-01
      • 2017-10-16
      • 2018-09-21
      • 1970-01-01
      • 2021-08-21
      • 2022-08-11
      • 1970-01-01
      相关资源
      最近更新 更多