A Simple Guide to Python 3 Urllib Post Data to Server – Python Tutorial

By | August 10, 2019

Python 3 urlib library can help us to access network, in this tutorial, we will introduce how to send our data to server with http post method. You can learn how to do by following our tutorial.

python post data to server

To send a data to sever with post method, you have three questions to solved.

How to build our data to send?

To send our data, we should format our data and build it can be sent.

We shoud build our data to be a dictionary

def buildData(file_name, image_name, page, size):
    data = {'filename':file_name, 'imagename':image_name, 'page': page, 'size':size}
    return data

In this function, we send file_name, image_name, page, size. We build them to be a python dictionary.

How to send our data to sever?

To send our data, we shoud encode our data firstly.

post_data = urllib.parse.urlencode(data).encode('utf-8')

Build an opener to send data

opener = getRequestOpener()

Notice: getRequestOpener() function is defined in here.

Best Practice to Python OpenDirector Add HTTP Request Header – Python Web Crawler Tutorial

Get http response to check our data is sent successful or not

    try:
        #ignore ssl        
        crawl_response = opener.open(url, data= post_data, timeout = 30)
    except Exception as e:
        print(e)
        crawl_response = None
    if not crawl_response:
        pass
    crawl_response_code = crawl_response.getcode()
    if crawl_response_code == 200:        
        content = getcontent(crawl_response)

Notice: getcontent() function is defined in here.

A Simple Guide to Get String Content from HTTP Response Header – Python Web Crawler Tutorial

Then we can anlysis content to check our data is sent to server successful or not.

Leave a Reply

Your email address will not be published. Required fields are marked *