使用request.post在Python中发送multipart表单数据无效

2 投票
1 回答
694 浏览
提问于 2025-04-18 10:01

我正在尝试使用这个网站通过Python 2.7发送一个叫做multipart/form-data的请求。具体来说,我要上传一个文件(叫做'Practice.txt'),这个文件是FASTA格式的,基本上是这样的格式:

'>1(ENTER)STRINGOFSPECIFICCAPITALLETTERS' 

我还需要在这个网站的文本框中输入一些数据(不过我这次不打算填)。这个网站还有一些复选框选项,我想选择'Length''Net Charge''Aliphatic Index''Hydrophobicity'。页面底部有一个'Submit'按钮。
目前,我用来发送POST请求的代码是这样的:

files = {'file': ('Practice.txt', open('Practice.txt', 'rb'))}
data = {'Length':'Length', 'Net Charge':'Net Charge', 'Aliphatic Index':'Aliphatic Index','Hydrophobicity':'Hydrophobicity'}
r = requests.post(url, files=files, data=data)
r.text

问题是,当我使用r.text时,什么数据都没有返回。用浏览器访问这个网站时,它会计算出所有这些值。我使用了WireShark,试图查看实时数据流,看看我到底发送了什么给服务器,虽然我用的代码和上面的一模一样,但它没有返回浏览器能得到的值。

有没有人知道为什么会这样,或者怎么才能获取到数据?谢谢大家的建议!

1 个回答

3

这个方法可以用:

import requests
import urllib

session = requests.Session()

file={'file':(open('practice.txt','r').read())}

url = 'http://www.camp.bicnirrh.res.in/featcalc/tt1.php'

payload = {
  'length'   :'length',     #Length
  'netcharge':'netcharge',  #Net Charge
  'aliphatic':'aliphatic',  #Aliphatic Index
  'gravy'    :'gravy'       #Hydrophobicity
  }

raw = urllib.urlencode(payload)

response = session.post(url, files=file, data=payload)

print(response.text)

所有选项:

payload = {
  'length'     :'length',      #Length
  'netcharge'  :'netcharge',   #Net Charge
  'amino'      :'amino',       #Amino acid composition
  'aliphatic'  :'aliphatic',   #Aliphatic Index
  'instability':'instability', #Instability Index
  'gravy'      :'gravy',       #Hydrophobicity
  'sec'        :'sec'          #Secondary Structure Propensity
  }

撰写回答