'Find the CSRF token from head tag in htlm using Beautifulsoup

HTML looks like this:

<head csrf-token="eCUDIDdtOwAHTgR4WE9ZWydwIAYvKQYIFRtXKWw7Nn4=...">

I was trying to extract this way:

token = soup.find('input', {'name':'csrfToken'})['value']

I keep getting:

TypeError: 'NoneType' object is not subscriptable

How to extract this token?



Solution 1:[1]

Your tag is head not input, so adjust your selection and to get the value of the attribute, use its name:

soup.find('head')['csrf-token']

or with css selectors

soup.select_one('head')['csrf-token']

Output:

eCUDIDdtOwAHTgR4WE9ZWydwIAYvKQYIFRtXKWw7Nn4=...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1