0

这是一段代码:

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 的项目,我不想# type: ignore在每次find_all -> ResultSet迭代中都使用它。

4

1 回答 1

0

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

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

但我对其他解决方案持开放态度。

于 2021-08-20T12:26:38.730 回答