Pylance正在从BeautifulSoup检测find_all>ResultSet中的PageElement而不是标记

2024-09-29 02:19:51 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一段代码:

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消息:

Cannot access member "get" for type "PageElement"

Member "get" is unknown Pylance(reportGeneralTypeIssues)

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


Tags: nameformforgetresponseformsallfind
1条回答
网友
1楼 · 发布于 2024-09-29 02:19:51

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

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

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

相关问题 更多 >