'I've been trying to scrape profile pictures in Instagram using this code but i keep getting TypeError: 'NoneType' object is not subscriptable

import requests
from bs4 import BeautifulSoup as bs
User = input("input the username of the user ");
url = 'https://instagram.com/' + User +'/'
r = requests.get(url)
alt = User + '\'s profile picture'
soup = bs(r.content, 'html.parser')
userImage = soup.find('img',{'alt': alt})['src']
print(userImage)

the code above is what I'm using this is written in python the line thats giving me issues is the one that says userImage = soup.find('img',{'alt': alt})['src']



Solution 1:[1]

Beautiful soup is unable to find the element you specified, so find is returning None. Then, when you index it with 'src', it tells you that a NoneType is not subscriptable. Make sure the element you're looking for actually exists and your argument to find is correct.

Solution 2:[2]

import urllib.parse
import urllib.request
import requests
def profilephoto(username):
    url = 'https://www.instagram.com/' + username+"/?__a=1"
    r = requests.get(url).text

    start = '"profile_pic_url_hd":"'
    end = '","requested_by_viewer":'
    profilepic = r[r.find(start) + len(start):r.rfind(end)]

    profilepicurl = profilepic.replace("\\u0026", "&")
    if len(profilepicurl)>0:
        resource = urllib.request.urlopen(profilepicurl)
        output = open(username+".jpg", "wb")
        output.write(resource.read())
        output.close()

  return

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 Tyler Liu
Solution 2 Zeliha Ergül