【问题标题】:Pylance is detecting PageElement instead of Tag in find_all -> ResultSet from BeautifulSoupPylance 正在从 BeautifulSoup 的 find_all -> ResultSet 中检测 PageElement 而不是 Tag
【发布时间】:2021-08-20 11:43:06
【问题描述】:

这是一段代码:

def prepare_security_questions(self, response: requests.Response) -> dict[str, str]:
    soup = BeautifulSoup(response.text, 'html.parser')

    form: dict[str, Any] = {}

    soup_forms = soup.find_all('form')
    soup_form = None
    for soup_possible_form in soup_forms:
        name = soup_possible_form.get('name')

问题是,当我检查soup_possible_form 的类型时,Pylance 显示它是一个不正确的PageElement 对象,它应该是一个Tag 对象,因此name = soup_possible_form.get('name') 被标记为一个错误,因为根据 Pylance 消息:

无法访问类型“PageElement”的成员“get”

“get”成员未知Pylance(reportGeneralTypeIssues)

我正在做一个我大量使用 BeautifulSoup 的项目,我不想在每次 find_all -> ResultSet 迭代中都使用 # type: ignore

【问题讨论】:

    标签: python visual-studio-code beautifulsoup pylance


    【解决方案1】:

    好吧,我找到了一个可能的解决方案,我在以下所有代码之前检查了每个元素的类型:

    for soup_possible_form in soup_forms:
        if not isinstance(soup_possible_form, Tag):
            continue
        
        name = soup_possible_form.get('name')
    

    但我愿意接受其他解决方案。

    【讨论】:

      猜你喜欢
      • 2016-12-19
      • 2013-03-30
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 2019-03-30
      • 1970-01-01
      • 1970-01-01
      • 2017-06-30
      相关资源
      最近更新 更多