2014-05-11 1 views
2

http://www.tinyupload.com/에 파일을 업로드하는 프로그램을 작성하고자하므로 양식을 업로드하는 방법을 검색했습니다. 내가 파일을 업로드하는 코드를 작성했습니다 :urllib.request를 사용하여 파일 업로드 tinyupload.com

import urllib.request 
import urllib.parse 
import http.cookiejar 
import re 

# Use cookies 
cookie = http.cookiejar.CookieJar() 
urllib.request.install_opener(urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookie))) 

# A function to download an url (GET) 
def urldownload(url): 
    try: 
     page = urllib.request.urlopen(url) 
     return page.read().decode('iso-8859-2') 
    except urllib.error.HTTPError: 
     return False 

# Get the url from the form to upload 
def geturl(html): 
     regex = re.compile('\<form action="(.*?)\" name="upload_form"', re.S) 
     url = regex.findall(html)[0] 
     return(str(url)) 

# Get the sid from the url 
def getsessionid(url): 
     return url[-26:] 

# Upload a file 
def upload(file): 
    url = geturl(urldownload('http://s000.tinyupload.com/index.php')) 
    sessionid = getsessionid(url) 
    f = open(file).read() 
    data = {'MAX_FILE_SIZE': '52428800', 
      'uploaded_file': f, 
      'file_description': 'File: %s' % (file), 
      'sessionid': sessionid} 
    data = urllib.parse.urlencode(data) 
    result = urllib.request.urlopen(url, data.encode('iso-8859-2')) 
    return(result.read().decode('iso-8859-2')) 
    #return(str(result.info())) 

내가 파일을 다운로드 할 수있는 링크입니다 페이지로 이동해야하지만, 내가 양식을 가지고있다. 뭐가 잘못 되었 니??

답변

1

더 간단한 방법으로 파일을 업로드 할 수 있습니다. requests 라이브러리를 사용하십시오.

import requests 

session = requests.Session() 

index_url = 'http://s000.tinyupload.com/index.php' 
upload_url = 'http://s000.tinyupload.com/cgi-bin/upload.cgi?sid=' 

index_request = session.get(index_url) 
PHPSESSID = index_request.cookies['PHPSESSID'] 

files = {'file': open('bitcoin.pdf', 'rb')} 
r = requests.post(upload_url+PHPSESSID, files=files) 

#Print "File upload finished" page 
print r.text 

#Print download link 
import re 
print re.search('http://s000\.tinyupload.com/\?file_id=[^<]+',r.text).group(0) 
관련 문제