Search code examples
pythonbeautifulsouppython-requestsurllib

Error While downloading image from instagram


Hi everyone I am having İnvalid scheme and much error with this code

i am just trying to make a simple instagram image downloader from given url here is the code

import requests
from bs4 import BeautifulSoup

def get_response(url):
    r = requests.get(url)
    while not r.ok:
        return r.status_code
    return r.text

url = input('Enter Instagram URL: ')
response = get_response(url)

soup = BeautifulSoup(response,"lxml")

image = soup.find("meta", property="og:image")
image = str(image)
image = image.replace("amp;","")
print(image)                    ### Here is working fine when you click printed link it works 

r = requests.get(image)         ### Problem is at here
with open('cat3.jpg', 'wb') as f:
   f.write(r.content)

# https://www.instagram.com/p/CL1TxMRlhe7/ #sample cat image 

ERRORS LİSTED HERE

Traceback (most recent call last):

  File "D:\Python öğreniyorum\ana_dosya.py", line 20, in <module>
    r = requests.get(image)         ### Problem is at here

  File "C:\Users\Pc\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\api.py", line 76, in get
    return request('get', url, params=params, **kwargs)

  File "C:\Users\Pc\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\Pc\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)

  File "C:\Users\Pc\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\sessions.py", line 649, in send
    adapter = self.get_adapter(url=request.url)

  File "C:\Users\Pc\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\sessions.py", line 742, in get_adapter
    raise InvalidSchema("No connection adapters were found for {!r}".format(url))
requests.exceptions.InvalidSchema: No connection adapters were found for '<meta content="https://instagram.fsaw3-1.fna.fbcdn.net/v/t51.2885-15/e35/s1080x1080/155344637_426370308591690_7809000723152066300_n.jpg?tp=1&_nc_ht=instagram.fsaw3-1.fna.fbcdn.net&_nc_cat=106&_nc_ohc=sP6bYsFdL_0AX8yIuXZ&oh=a7e381762b429e6c7b3b494b510ca166&oe=60790CBF" property="og:image"/>'

Solution

  • As indicated in the very last line of your error message you are trying to send a request to a URL that is invalid. It is invalid because it contains the HTML tag meta. You have to grab the URL that is in the content attribute of the HTML code.

    Here is the code that you need in order to get the URL to the Instagram image:

    image = soup.find("meta", property="og:image")["content"]