Python - 使用urllib2开启者进行发布

时间:2012-11-19 05:37:05

标签: python urllib2

我有一个urllib2开启器,并希望将它用于带有一些数据的POST请求。

我希望收到我正在发布的页面的内容,以及返回的页面的URL(我认为这只是一个30x的代码;所以这些内容很棒!)。

将此视为代码:

anOpener = urllib2.build_opener(???,???)
anOpener.addheaders = [(???,???),(???,???),...,(???,???)]
# do some other stuff with the opener 
data = urllib.urlencode(dictionaryWithPostValues)
pageContent = anOpener.THE_ANSWER_TO_THIS_QUESTION
pageURL = anOpener.THE_SECOND_PART_OF_THIS_QUESTION

3 个答案:

答案 0 :(得分:6)

一旦人们意识到答案,这是一个非常愚蠢的问题。

只需使用:

open(URL,data)

第一部分,和Rachel Sanders提到的一样,

geturl()

第二部分。

我真的无法弄清楚整个请求/开启者的工作原理如何;我找不到任何好的文档:/

答案 1 :(得分:5)

此页面可以帮助您:

http://www.voidspace.org.uk/python/articles/urllib2.shtml#data

import urllib
import urllib2

url = 'http://www.someserver.com/cgi-bin/register.cgi'
values = {'name' : 'Michael Foord',
      'location' : 'Northampton',
      'language' : 'Python' }

data = urllib.urlencode(values)
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
the_page = response.read()
the_url  = response.geturl() # <- doc claims this gets the redirected url

看起来您也可以使用response.info()直接获取Location标头,而不是使用.geturl()。

希望有所帮助!

答案 2 :(得分:0)

如果向请求添加数据,则该方法会自动更改为POST。请查看以下示例:

import urllib2
import json

url = "http://server.local/x/y"
data = {"name":"JackBauer"}
method = "PUT"
request = urllib2.Request(url)
request.add_header("Content-Type", "application/json")
request.get_method = lambda: method
if data: request.add_data(json.dumps(data))
response = urllib2.urlopen(request)
if response: print response.read()

正如我所提到的,如果您使用GET / POST,则不需要lambda。

相关问题