簡體   English   中英

Python:僅使用原始字符串發送POST請求

[英]Python: Send a POST request using just a raw string

我想只使用原始字符串發送POST請求。

我正在寫一個解析器。 我已經加載了頁面,並在firebug中看到了許多標題和正文的復雜請求:

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

如何再次發送此確切請求(標題+帖子正文)手動(將其作為一個巨大的字符串傳遞)?

喜歡:

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

我希望它由我的腳本發送(和響應處理),並且不想手動創建參數和標題的字典。

謝謝。

另一個答案太大而且令人困惑,而且顯示的不僅僅是你所要求的。 我覺得我應該為未來的讀者提供一個更簡潔的答案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM