Pylance is detecting PageElement instead of Tag in find_all -> ResultSet from BeautifulSoup

Viewed 193

This is a fragment of code:

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')

The problem is, when i check the type of soup_possible_form, Pylance shows that it is a PageElement object which is incorrect, it should be a Tag object, and because of that name = soup_possible_form.get('name') is marked as an error because according to Pylance message:

Cannot access member "get" for type "PageElement"

Member "get" is unknown Pylance(reportGeneralTypeIssues)

I'm working on a project where i heavily use BeautifulSoup and i don't want to use # type: ignore on every find_all -> ResultSet iteration.

1 Answers

Alright i found a possible solution, i checked the type of each element before all the following code:

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

But i'm open for other solutions.

Related