LANshark
LANshark

Reputation: 75

Can't Seem To Get POST Requests Working In Python 3

I'm attempting to write a script that will allow me to upload an image to BayImg, but I can't seem to get it to work right. As far as I can tell, I'm not getting any result. I don't know if it's not submitting the data or what, but when I print the response, I get the URL of the home page, not the page you get when you upload a picture. If I were using Python 2.x, I would use Mechanize. However, it's not available for Py3k, so I'm attempting to use urllib. I'm using Python 3.2.3. Here is the code:

    #!/usr/bin/python3

    from urllib.parse import urlencode
    from urllib.request import Request, urlopen

    image = "/test.png"
    removal = "remove"
    tags = "python script test image"
    url = "http://bayimg.com/"
    values = {"code" : removal,
              "tags" : tags,
              "file" : image}

    data = urlencode(values).encode("utf-8")
    req = Request(url, data)
    response = urlopen(req)
    the_page = response.read()

Any assistance would be greatly appreciated.

Upvotes: 1

Views: 6945

Answers (2)

Dex
Dex

Reputation: 398

I came across this post and thought to improve it with the below solution. So here is a sample class written in Python3 that has POST method implemented using urllib.

import urllib.request
import json

from urllib.parse import urljoin
from urllib.error import URLError
from urllib.error import HTTPError

class SampleLogin():

    def __init__(self, environment, username, password):
        self.environment = environment
        # Sample environment value can be: http://example.com
        self.username = username
        self.password = password

    def login(self):
        sessionUrl = urljoin(self.environment,'/path/to/resource/you/post/to')
        reqBody = {'username' : self.username, 'password' : self.password}
        # If you need encoding into JSON, as per http://stackoverflow.com/questions/25491541/python3-json-post-request-without-requests-library
        data = json.dumps(reqBody).encode('utf-8')

        headers = {}
        # Input all the needed headers below
        headers['User-Agent'] = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36"
        headers['Accept'] = "application/json"
        headers['Content-type'] = "application/json"

        req = urllib.request.Request(sessionUrl, data, headers)

        try: 
            response = urllib.request.urlopen(req)
            return response
        # Then handle exceptions as you like.
        except HTTPError as httperror:
            return httperror
        except URLError as urlerror:
            return urlerror
        except:
            logging.error('Login Error')

Upvotes: 1

Kabie
Kabie

Reputation: 10653

  1. You need to POST the data
  2. You need to know the right url, check the html source, in this case:http://upload.bayimg.com/upload
  3. You need read the content of the file instead of only pass the filename

You might want use Requests to do it easily.

Upvotes: 3

Related Questions