2012-05-14 27 views
1

我正在嘗試編寫一個腳本,允許我將圖像上傳到BayImg,但我似乎無法讓它正常工作。據我所知,我沒有得到任何結果。我不知道它是否不提交數據或內容,但是當我打印回覆時,我會得到主頁的URL,而不是您上傳圖片時得到的頁面。如果我使用Python 2.x,我會使用Mechanize。但是,它不適用於Py3k,所以我試圖使用urllib。我正在使用Python 3.2.3。這裏是代碼:看不到要獲取POST請求在Python 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() 

任何援助將不勝感激。

回答

3
  1. 您需要POST數據
  2. 你需要知道正確的網址,查看HTML源,在這種情況下:http://upload.bayimg.com/upload
  3. 你需要讀取文件的內容,而不是僅僅通過文件名

您可能希望使用Requests輕鬆完成此操作。

+1

按照建議使用請求,效果很好。萬分感謝! – LANshark

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