似乎无法让POST请求在Python 3中工作

2024-05-15 20:45:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个脚本,允许我将图像上载到BayImg,但似乎无法使其正常工作。据我所知,我没有任何结果。我不知道它是否没有提交数据或什么,但是当我打印响应时,我得到的是主页的URL,而不是上传图片时得到的页面。如果我使用Python2.x,我将使用Mechanize。但是,它不适用于Py3k,所以我尝试使用urllib。我正在使用Python3.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()

如有任何帮助,将不胜感激。


Tags: fromtestimageimporturldataresponserequest
2条回答

我碰到这篇文章,想用下面的解决方案来改进它。这里有一个用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')
  1. 你需要POST数据
  2. 你需要知道正确的url,检查html源代码,在这种情况下:http://upload.bayimg.com/upload
  3. 您需要读取文件的内容,而不是只传递文件名

您可能需要使用Requests来轻松完成。

相关问题 更多 >