Home > Mobile >  getting error when send a post request in python
getting error when send a post request in python

Time:10-06

i want scrap a web and also send data and scrap again, but in the first step when i want send a post method a get error this is my code

import requests

url = "https://tracking.post.ir/"
h = "Mozilla/5.0 (Linux; Android 7.0.0; SM-G960F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36"
dat = {"test": "test"}
requests.post(url, data=dat, headers=h)

and this is my 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 5, in <module>
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/requests/api.py", line 119, in post
    return 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/api.py", line 61, in request
    return session.request(method=method, url=url, **kwargs)  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/requests/sessions.py", line 528, in request
    prep = self.prepare_request(req)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/requests/sessions.py", line 456, in prepare_request
    p.prepare(
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/requests/models.py", line 317, in prepare
    self.prepare_headers(headers)
  File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.8/site-packages/requests/models.py", line 449, in prepare_headers
    for header in headers.items():
AttributeError: 'str' object has no attribute 'items'

[Program finished]

also i dont know urllib in python

CodePudding user response:

What the error is telling you is that headers needs to be a dictionary, items is the dictionary method to produce tuple pairs of keys and values.

To make a POST request with requests you have to

import requests

url = "https://tracking.post.ir/"

h = {
  "User-Agent": "Mozilla/5.0 (Linux; Android 7.0.0; SM-G960F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.84 Mobile Safari/537.36"
}

dat = {"test": "test"}

respose = requests.post(url, data=dat, headers=h)

# Do something with response here

Docs

  • Related