是否urllib2支持DELETE或PUT方法?如果是,请提供任何示例.我需要使用活塞API.
我很熟悉我应该将HTTP_RPOXY环境变量设置为代理地址.
一般urllib工作正常,问题是处理urllib2.
>>> urllib2.urlopen("http://www.google.com").read()
Run Code Online (Sandbox Code Playgroud)
回报
urllib2.URLError: <urlopen error [Errno 10061] No connection could be made because the target machine actively refused it>
Run Code Online (Sandbox Code Playgroud)
要么
urllib2.URLError: <urlopen error [Errno 11004] getaddrinfo failed>
Run Code Online (Sandbox Code Playgroud)
我试过@Fenikso的答案,但我现在收到这个错误:
URLError: <urlopen error [Errno 10060] A connection attempt failed because the
connected party did not properly respond after a period of time, or established
connection failed because connected host has failed to respond>
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
如何使用Python的urllib2创建"保持活跃"的HTTP请求?
我正在编写一些与redmine接口的代码,我需要上传一些文件作为过程的一部分,但我不知道如何从包含二进制文件的python中执行POST请求.
我试图在这里模仿命令:
curl --data-binary "@image.png" -H "Content-Type: application/octet-stream" -X POST -u login:password http://redmine/uploads.xml
Run Code Online (Sandbox Code Playgroud)
在python(下面)中,它似乎不起作用.我不确定问题是否与编码文件有关,或者标题是否有问题.
import urllib2, os
FilePath = "C:\somefolder\somefile.7z"
FileData = open(FilePath, "rb")
length = os.path.getsize(FilePath)
password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm()
password_manager.add_password(None, 'http://redmine/', 'admin', 'admin')
auth_handler = urllib2.HTTPBasicAuthHandler(password_manager)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
request = urllib2.Request( r'http://redmine/uploads.xml', FileData)
request.add_header('Content-Length', '%d' % length)
request.add_header('Content-Type', 'application/octet-stream')
try:
response = urllib2.urlopen( request)
print response.read()
except urllib2.HTTPError as e:
error_message = e.read()
print error_message
Run Code Online (Sandbox Code Playgroud)
我有权访问服务器,它看起来像编码错误:
...
invalid byte sequence in UTF-8
Line: 1
Position: …Run Code Online (Sandbox Code Playgroud) 我正在构建一个"API API",它基本上是内部REST Web服务的包装器,Web应用程序将向其发出大量请求.一些Web服务调用需要是GET而不是post,而是传递参数.
是否有"最佳实践"方法将字典编码为查询字符串?例如:?foo=bar&bla=blah
我正在查看urllib2文档,看起来它本身决定使用POST或GET基于你是否传递params,但也许有人知道如何使它将params字典转换为GET请求.
也许这里有类似的东西?如果它支持keep-alive将会很棒,因为Web服务器将不断地从REST服务请求内容.
理想情况下,还可以将XML转换为某种可遍历的python对象.
谢谢!
我尝试使用Python的urllib获取维基百科文章:
f = urllib.urlopen("http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes")
s = f.read()
f.close()
Run Code Online (Sandbox Code Playgroud)
然而,而不是HTML页面,我得到以下响应:错误 - 维基媒体基金会:
Request: GET http://en.wikipedia.org/w/index.php?title=Albert_Einstein&printable=yes, from 192.35.17.11 via knsq1.knams.wikimedia.org (squid/2.6.STABLE21) to ()
Error: ERR_ACCESS_DENIED, errno [No Error] at Tue, 23 Sep 2008 09:09:08 GMT
Run Code Online (Sandbox Code Playgroud)
维基百科似乎阻止了不是来自标准浏览器的请求.
有谁知道如何解决这个问题?
为了对URI进行编码,我使用urllib.quote("schönefeld")但是当字符串中存在一些非ascii字符时,它就是Thorws
KeyError: u'\xe9'
Code: return ''.join(map(quoter, s))
Run Code Online (Sandbox Code Playgroud)
我的输入字符串köln, brønshøj, schönefeld等.
当我尝试在Windows中打印语句时(使用python2.7,pyscripter IDE).但是在linux中它会引发异常(我猜平台并不重要).
这就是我想要的:
from commands import getstatusoutput
queryParams = "schönefeld";
cmdString = "http://baseurl" + quote(queryParams)
print getstatusoutput(cmdString)
Run Code Online (Sandbox Code Playgroud)
探索问题的原因:
在urllib.quote(),其实在异常被肆意return ''.join(map(quoter, s)).
urllib中的代码是:
def quote(s, safe='/'):
if not s:
if s is None:
raise TypeError('None object cannot be quoted')
return s
cachekey = (safe, always_safe)
try:
(quoter, safe) = _safe_quoters[cachekey]
except KeyError:
safe_map = _safe_map.copy()
safe_map.update([(c, c) for c in safe])
quoter = …Run Code Online (Sandbox Code Playgroud) 我想这必须有一个简单的答案,但我正在努力:我想拿一个url(输出json)并在python中的可用字典中获取数据.我被困在最后一步.
>>> import urllib2
>>> import simplejson
>>> req = urllib2.Request("http://vimeo.com/api/v2/video/38356.json", None, {'user-agent':'syncstream/vimeo'})
>>> opener = urllib2.build_opener()
>>> f = opener.open(req)
>>> f.read() # this works
'[{"id":"38356","title":"Forgetfulness - Billy Collins Animated Poetry","description":"US Poet Laureate Billy Collins reads his poem ","url":"http:\\/\\/vimeo.com\\/38356","upload_date":"2006-01-24 15:21:03","thumbnail_small":"http:\\/\\/80.media.vimeo.com\\/d1\\/5\\/47\\/74\\/thumbnail-4774968.jpg","thumbnail_medium":"http:\\/\\/80.media.vimeo.com\\/d1\\/5\\/46\\/85\\/thumbnail-4685118.jpg","thumbnail_large":"http:\\/\\/images.vimeo.com\\/87\\/39\\/873998\\/873998_640x480.jpg","user_name":"smjwt","user_url":"http:\\/\\/vimeo.com\\/smjwt","user_portrait_small":"http:\\/\\/bitcast.vimeo.com\\/vimeo\\/portraits\\/defaults\\/d.30.jpg","user_portrait_medium":"http:\\/\\/bitcast.vimeo.com\\/vimeo\\/portraits\\/defaults\\/d.75.jpg","user_portrait_large":"http:\\/\\/bitcast.vimeo.com\\/vimeo\\/portraits\\/defaults\\/d.100.jpg","user_portrait_huge":"http:\\/\\/bitcast.vimeo.com\\/vimeo\\/portraits\\/defaults\\/d.300.jpg","stats_number_of_likes":"281","stats_number_of_plays":"9173","stats_number_of_comments":23,"duration":"112","width":"320","height":"240","tags":"poetry, poet, online poetry, famous poet, video poetry, modern poetry, famous poem, poetry sites, poetry websites, audio poetry, american poet, animation clips, american poetry, free poetry sites, animation art, free poetry, animated clips, poem, poet laureate"}]'
>>> simplejson.load(f)
Traceback (most …Run Code Online (Sandbox Code Playgroud) 我想使用urllib下载文件并在保存之前将文件解压缩到内存中.
这就是我现在所拥有的:
response = urllib2.urlopen(baseURL + filename)
compressedFile = StringIO.StringIO()
compressedFile.write(response.read())
decompressedFile = gzip.GzipFile(fileobj=compressedFile, mode='rb')
outfile = open(outFilePath, 'w')
outfile.write(decompressedFile.read())
Run Code Online (Sandbox Code Playgroud)
这最终会写出空文件.我怎样才能实现我追求的目标?
更新答案:
#! /usr/bin/env python2
import urllib2
import StringIO
import gzip
baseURL = "https://www.kernel.org/pub/linux/docs/man-pages/"
# check filename: it may change over time, due to new updates
filename = "man-pages-5.00.tar.gz"
outFilePath = filename[:-3]
response = urllib2.urlopen(baseURL + filename)
compressedFile = StringIO.StringIO(response.read())
decompressedFile = gzip.GzipFile(fileobj=compressedFile)
with open(outFilePath, 'w') as outfile:
outfile.write(decompressedFile.read())
Run Code Online (Sandbox Code Playgroud) 我想知道,你如何关闭与Requests(python-requests.org)的连接?
有了httplib它HTTPConnection.close(),但我如何对请求做同样的事情?
代码如下:
r = requests.post("https://stream.twitter.com/1/statuses/filter.json", data={'track':toTrack}, auth=('username', 'passwd'))
for line in r.iter_lines():
if line:
self.mongo['db'].tweets.insert(json.loads(line))
Run Code Online (Sandbox Code Playgroud)
提前致谢.