0

This is my code in a function:

def tri():
    import requests, json, urllib.parse
    
    username = "usernam"
    password = "pass"
    r = requests.Session()
    hd={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:81.0) Gecko/20100101 Firefox/81.0'}
    res = r.get('https://www.instagram.com/', headers=hd)
    payload = {'username':username,'enc_password':'#PWD_INSTAGRAM_BROWSER:0:1254625879:'+password,'queryParams':'{}','optIntoOneTap':'false'}
    headers_text = '''Host: www.instagram.com
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0
    Accept: */*
    Accept-Language: en-US,en;q=0.5
    Accept-Encoding: gzip, deflate, br
    X-CSRFToken: %s
    X-IG-WWW-Claim: 0
    Content-Type: application/x-www-form-urlencoded
    X-Requested-With: XMLHttpRequest
    Content-Length: %s
    Origin: https://www.instagram.com
    Referer: https://www.instagram.com/
    Cookie: ig_did=%s; csrftoken=%s; mid=%s
    TE: Trailers'''%(res.cookies['csrftoken'],str(len(urllib.parse.urlencode(payload))),res.cookies['ig_did'],res.cookies['csrftoken'],res.cookies['mid'])
    payload_headers = {i.split(': ')[0]:i.split(': ')[1] for i in headers_text.split('\n')}
    resp = r.post("https://www.instagram.com/accounts/login/ajax/", headers=payload_headers,data=payload)
    if json.loads(resp.text)["authenticated"] == True:
        print('[+] Login successfully!')
        #print(resp.text)
    else:
        print(json.loads(resp.text))
        #print(word)

tri()

I want to login to Instagram via python requests library, and my code work well without function or loop but when I put my code under a function or loop like this, my code gets this error:

Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
    start(fakepyfile,mainpyfile)
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
    exec(open(mainpyfile).read(),  __main__.__dict__)
  File "<string>", line 40, in <module>
  File "<string>", line 32, in tri
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/requests/sessions.py", line 590, in post
    return self.request('POST', url, data=data, json=json, **kwargs)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/requests/sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/requests/sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/requests/adapters.py", line 439, in send
    resp = conn.urlopen(
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/urllib3/connectionpool.py", line 699, in urlopen
    httplib_response = self._make_request(
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/urllib3/connectionpool.py", line 394, in _make_request
    conn.request(method, url, **httplib_request_kw)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/urllib3/connection.py", line 234, in request
    super(HTTPConnection, self).request(method, url, body=body, headers=headers)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/http/client.py", line 1240, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/http/client.py", line 1281, in _send_request
    self.putheader(hdr, value)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/urllib3/connection.py", line 219, in putheader
    _HTTPConnection.putheader(self, header, *values)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/http/client.py", line 1208, in putheader    raise ValueError('Invalid header name %r' % (header,))
ValueError: Invalid header name b'\tUser-Agent'

I don't know what's going on. I want to put my code into a function or loop. Also I'm coding in Android.

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 1
    Your `headers_text` variables contain tab characters because it's indented. Multiline strings are literal and include all newlines and spaces. – Woodford Aug 24 '21 at 17:18

1 Answers1

0

Your headers_text variable contain tab characters because it's indented. Multiline strings are literal and include all newlines and spaces.

Remove the indentation or construct your string another way.

    headers_text = '''Host: www.instagram.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0
Accept: */*
...
'''

# or...

    headers_text = (
    "Host: www.instagram.com\n"
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0\n"
    "Accept: */*\n")
    ...

# or... (less better)

    headers_text = "Host: www.instagram.com\n" \
    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:80.0) Gecko/20100101 Firefox/80.0\n" \
    "Accept: */*\n" \
    ...
Woodford
  • 3,746
  • 1
  • 15
  • 29
  • You'll need braces in that second example `a = ("a\n" \n "b\n" \n ... )`. Otherwise it will just be strings executed as a statement on their own. – flakes Aug 24 '21 at 17:23
  • @flakes Indeed, thanks! Line continuation seems like a slightly better choice. – Woodford Aug 24 '21 at 17:25
  • I would avoid backslashes. PEP8 seems to agree: "The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation." Basically only use them if you can't use anything else. https://python.org/dev/peps/pep-0008/#maximum-line-length – flakes Aug 24 '21 at 17:26