使代码成为函数或循环后出错

Getting error after making code a function or loop

这是我在函数中的代码:

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

我想通过 python 请求库登录 Instagram,我的代码在没有函数或循环的情况下运行良好,但是当我将我的代码放在这样的函数或循环下时,我的代码出现此错误:

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'

我不知道发生了什么。 我想将我的代码放入一个函数或循环中。 我也在 Android.

中编码

您的 headers_text 变量包含制表符,因为它是缩进的。多行字符串是文字,包括所有换行符和空格。

删除缩进或以其他方式构建字符串。

    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" \
    ...