首页 > 解决方案 > 类型错误“类型”对象的 Python 脚本问题不可迭代

问题描述

我有这个 email_check 类,我用它作为我拥有的脚本的一部分,最近它一直在抛出错误。我不得不对代码进行更改,因为它曾经使用 google plus 并且因此引发错误,我从下面代码中的 for 语句中删除了 google plus,现在我得到了 Type Error 'Type' 对象是不可迭代的。这是代码:

from scraper.config import Config
# from scraper.google_plus import GooglePlus
from scraper.scraper import Scraper
from scraper.spokeo import Spokeo


class EmailChecker:
    def __init__(self):
        config = Config()

        # Open instance to chromedriver
        self.__scraper = Scraper()

    def check_email(self, email):
        config = Config()
        results = {}

        # for _ in (GooglePlus, Spokeo):
        for _ in (Spokeo):
            site = _(self.__scraper)

            try:
                result = site.search_for_email(email)
            except Exception:
                if config.debug:
                    raise
                result = None

            try:
                site.logout()
            except Exception:
                if config.debug:
                    raise
                pass

            results[_.__name__] = result

        try:
            self.__scraper.driver.close()
        except Exception:
            pass

        try:
            self.__scraper.driver.quit()
        except Exception:
            pass

        return results

标签: pythonpython-3.x

解决方案


(GooglePlus, Spokeo)是一个元组,可以for循环迭代。(Spokeo)是括号内的表达式,仅用于表示优先级。举一个更具体的例子,考虑(2 + 3, 1)(计算结果为(5, 1))与(2 + 3)(计算结果为 5)。

为了尽可能少地更改代码,您可以只编写(Spokeo,)而不是使用(Spokeo)单元组,尽管这有点奇怪的语法。由于您不再迭代任何内容,因此您可以删除 for 循环:

results = {}

_ = Spokeo # the old for was here

site = _(self.__scraper)

...

但考虑有一个比_. 或者只是删除该变量并Spokeo在其位置显式使用:site = Spokeo(self.__scraper)等等。


推荐阅读