似乎无法在Python 3中获取POST请求

时间:2012-05-14 00:54:21

标签: python http post python-3.x urllib

我正在尝试编写一个脚本,允许我将图像上传到BayImg,但我似乎无法让它正常工作。据我所知,我没有得到任何结果。我不知道它是不是提交数据或者是什么,但是当我打印响应时,我得到的是主页的URL,而不是上传图片时得到的页面。如果我使用的是Python 2.x,我会使用Mechanize。但是,它不适用于Py3k,所以我试图使用urllib。我正在使用Python 3.2.3。这是代码:

    #!/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()

非常感谢任何协助。

2 个答案:

答案 0 :(得分:3)

  1. 您需要POST数据
  2. 您需要知道正确的网址,检查html来源,在这种情况下:http://upload.bayimg.com/upload
  3. 您需要阅读文件内容而不是仅传递文件名
  4. 您可能希望使用Requests轻松完成此操作。

答案 1 :(得分:1)

我遇到了这篇文章,并考虑通过以下解决方案来改进它。所以这是一个用Python3编写的示例类,它使用urllib实现了POST方法。

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