Python:只使用原始字符串发送POST请求

2024-04-23 23:33:54 发布

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

我想用一个原始字符串发送一个POST请求。

我在写一个解析器。我已经加载了页面,在firebug中看到了一个非常复杂的请求,有很多头和体:

__EVENTTARGET=&__EVENTARGUMENT=&__VIEW.... (11Kb or unreadable text)

如何手动(将其作为一个巨大的字符串传递)再次发送这个确切的请求(headers+post body)?

比如:

func("%(headers) \n \n %(body)" % ... )

我希望它通过我的脚本发送(并处理响应),而不希望手动创建参数和头的字典。

谢谢你。


Tags: or字符串textview解析器body页面手动
2条回答

另一个答案太大了,让人困惑,而且比你要求的要多。我觉得我应该为未来的读者提供一个更简洁的答案:

import urllib2
import urllib
import urlparse

# this was the header and data strings you already had
headers = 'baz=3&foo=1&bar=2'
data = 'baz=3&foo=1&bar=2'

header_dict = dict(urlparse.parse_qsl(headers))

r = urllib2.Request('http://www.foo.com', data, headers)
resp = urllib2.urlopen(r)

您至少需要将头解析回dict,但它的工作量很小。然后把它传递给一个新的请求。

*注意:这个简洁的示例假定头和数据体都是application/x-www-form-urlencoded格式。如果头是原始字符串格式,如Key: Value,那么请参阅另一个答案,以获取有关首先解析该格式的更多详细信息。

最终,您不能只复制粘贴原始文本并运行新请求。它必须以适当的格式分为头和数据。

import urllib
import urllib2

# DATA:

# option #1 - using a dictionary
values = {'name': 'Michael Foord', 'location': 'Northampton', 'language': 'Python' }
data = urllib.urlencode(values)

# option #2 - directly as a string
data = 'name=Michael+Foord&language=Python&location=Northampton'

# HEADERS:

# option #1 - convert a bulk of headers to a dictionary (really, don't do this)    

headers = '''
Host: www.http.header.free.fr
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,
Accept-Language: Fr
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0)
Connection: Keep-Alive
'''

headers = dict([[field.strip() for field in pair.split(':', 1)] for pair in headers.strip().split('\n')])

# option #2 - just use a dictionary

headers = {'Accept': 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,',
           'Accept-Encoding': 'gzip, deflate',
           'Accept-Language': 'Fr',
           'Connection': 'Keep-Alive',
           'Host': 'www.http.header.free.fr',
           'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 4.0)'}

# send the request and receive the response

req = urllib2.Request('http://www.someserver.com/cgi-bin/register.cgi', data, headers)
response = urllib2.urlopen(req)
the_page = response.read()

相关问题 更多 >