如果我知道内容将是字符串,那么用Python进行HTTP GET的最快方法是什么? 我正在搜索文档,以查找像以下这样的快速单行代码:

contents = url.get("http://example.com/foo/bar")

但是我可以使用Google找到的只是httpliburllib我无法在这些库中找到快捷方式。

标准Python 2.5是否具有上述某种形式的快捷方式,还是应该编写url_get函数?

  1. 我宁愿不要捕获脱壳输出到wgetcurl的输出。

#1楼

您可以使用一个称为request的库。

import requests
r = requests.get("http://example.com/foo/bar")

这很容易。 然后您可以这样做:

>>> print(r.status_code)
>>> print(r.headers)
>>> print(r.content)

#2楼

theller的wget解决方案确实很有用,但是,我发现它无法在整个下载过程中打印出进度。 如果在reporthook中的print语句后添加一行,那是完美的。

import sys, urllibdef reporthook(a, b, c):print "% 3.1f%% of %d bytes\r" % (min(100, float(a * b) / c * 100), c),sys.stdout.flush()
for url in sys.argv[1:]:i = url.rfind("/")file = url[i+1:]print url, "->", fileurllib.urlretrieve(url, file, reporthook)
print

#3楼

如果您专门使用HTTP API,那么还有更方便的选择,例如Nap 。

例如,以下是自20145月1日起从Github获取要点的方法:

from nap.url import Url
api = Url('https://api.github.com')gists = api.join('gists')
response = gists.get(params={'since': '2014-05-01T00:00:00Z'})
print(response.json())

更多示例: https : //github.com/kimmobrunfeldt/nap#examples


#4楼

出色的解决方案轩,塞勒。

为了使其与python 3配合使用,请进行以下更改

import sys, urllib.requestdef reporthook(a, b, c):print ("% 3.1f%% of %d bytes\r" % (min(100, float(a * b) / c * 100), c))sys.stdout.flush()
for url in sys.argv[1:]:i = url.rfind("/")file = url[i+1:]print (url, "->", file)urllib.request.urlretrieve(url, file, reporthook)
print

另外,您输入的URL之前应带有“ http://”,否则将返回未知的URL类型错误。


#5楼

无需其他必要的导入,此解决方案(对我而言)有效-也适用于https:

try:import urllib2 as urlreq # Python 2.x
except:import urllib.request as urlreq # Python 3.x
req = urlreq.Request("http://example.com/foo/bar")
req.add_header('User-Agent', 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36')
urlreq.urlopen(req).read()

在标头信息中未指定“ User-Agent”时,通常很难抓住内容。 然后通常使用类似以下内容来取消请求: urllib2.HTTPError: HTTP Error 403: Forbiddenurllib.error.HTTPError: HTTP Error 403: Forbidden


#6楼

如何发送标头

Python 3:

import urllib.request
contents = urllib.request.urlopen(urllib.request.Request("https://api.github.com/repos/cirosantilli/linux-kernel-module-cheat/releases/latest",headers={"Accept" : 'application/vnd.github.full+json"text/html'}
)).read()
print(contents)

Python 2:

import urllib2
contents = urllib2.urlopen(urllib2.Request("https://api.github.com",headers={"Accept" : 'application/vnd.github.full+json"text/html'}
)).read()
print(contents)

#7楼

使用urllib3很简单。

像这样导入它:

import urllib3pool_manager = urllib3.PoolManager()

并发出这样的请求:

example_request = pool_manager.request("GET", "https://example.com")print(example_request.data.decode("utf-8")) # Response text.
print(example_request.status) # Status code.
print(example_request.headers["Content-Type"]) # Content type.

您也可以添加标题:

example_request = pool_manager.request("GET", "https://example.com", headers = {"Header1": "value1","Header2": "value2"
})

#8楼

Python 3:

import urllib.request
contents = urllib.request.urlopen("http://example.com/foo/bar").read()

Python 2:

import urllib2
contents = urllib2.urlopen("http://example.com/foo/bar").read()

urllib.requestread文档。


#9楼

看一下httplib2 ,它旁边有许多非常有用的功能,可提供所需的功能。

import httplib2resp, content = httplib2.Http().request("http://example.com/foo/bar")

其中content是响应主体(作为字符串),而resp将包含状态和响应标头。

虽然它不包含在标准python安装中(但仅需要标准python),但是绝对值得一试。


#10楼

如果您希望使用httplib2的解决方案成为一体,请考虑实例化匿名Http对象。

import httplib2
resp, content = httplib2.Http().request("http://example.com/foo/bar")

#11楼

这是Python中的wget脚本:

# From python cookbook, 2nd edition, page 487
import sys, urllibdef reporthook(a, b, c):print "% 3.1f%% of %d bytes\r" % (min(100, float(a * b) / c * 100), c),
for url in sys.argv[1:]:i = url.rfind("/")file = url[i+1:]print url, "->", fileurllib.urlretrieve(url, file, reporthook)
print

在Python中最快的HTTP GET方法是什么?相关推荐

  1. Python 中 异步协程 的 使用方法介绍

    静觅 崔庆才的个人博客:Python中异步协程的使用方法介绍:https://cuiqingcai.com/6160.html Python 异步 IO .协程.asyncio.async/await ...

  2. python list方法说明_对python中list的五种查找方法说明

    Python中是有查找功能的,五种方式:in.not in.count.index,find 前两种方法是保留字,后两种方式是列表的方法. 下面以a_list = ['a','b','c','hell ...

  3. python list find函数_对python中list的五种查找方法说明

    Python中是有查找功能的,五种方式:in.not in.count.index,find 前两种方法是保留字,后两种方式是列表的方法. 下面以a_list = ['a','b','c','hell ...

  4. Python中的数据可视化工具与方法——常用的数据分析包numpy、pandas、statistics的理解实现和可视化工具matplotlib的使用

    Python中的数据可视化工具与方法 本文主要总结了: 1.本人在初学python时对常用的数据分析包numpy.pandas.statistics的学习理解以及简单的实例实现 2.可视化工具matp ...

  5. python创建类的实例方法-Python中动态创建类实例的方法

    简介 在Java中我们可以通过反射来根据类名创建类实例,那么在Python我们怎么实现类似功能呢? 其实在Python有一个builtin函数import,我们可以使用这个函数来在运行时动态加载一些模 ...

  6. Python中os和shutil模块实用方法集锦

    Python中os和shutil模块实用方法集锦 类型:转载 时间:2014-05-13 这篇文章主要介绍了Python中os和shutil模块实用方法集锦,需要的朋友可以参考下 复制代码代码如下: ...

  7. python中的class怎么用_对python 中class与变量的使用方法详解

    python中的变量定义是很灵活的,很容易搞混淆,特别是对于class的变量的定义,如何定义使用类里的变量是我们维护代码和保证代码稳定性的关键. #!/usr/bin/python #encoding ...

  8. python中怎么输出中文-python中使用print输出中文的方法

    看Python简明教程,学习使用print打印字符串,试了下打印中文,不行. 编辑环境:IDLE 上网搜了下解决办法,各种说法,试了两种: print u"学习" print (u ...

  9. python if语句多个条件-Python中if有多个条件处理方法

    Python中if有多个条件怎么办 python中if有多个条件,可以使用and.or.elif关键字来连接. Python 编程中 if 语句用于控制程序的执行,基本形式为: if 判断条件: 执行 ...

最新文章

  1. Office OpenXML-Excel(一)
  2. InnoDB调优-索引优化策略
  3. vue常见问题随笔集
  4. java 多项式拟合最多的项数_机器学习(1)--线性回归和多项式拟合
  5. OO实现ALV TABLE 五:ALV的栏位属性
  6. golang reflect
  7. 从五个维度来计算互联网产品单个用户的价值
  8. xampp里mysql的环境变量配置_XAMPP集成环境中MySQL数据库的使用
  9. l298n使能端跳线帽_L298N 驱动模块的应用
  10. 一元线性回归原理及代码实现
  11. 实现一个基于XDP/eBPF的学习型网桥
  12. javaMail学习二 电子邮件的工作原理
  13. 曲面局部理论介绍——从曲面的概念、基本形式到高斯曲率及其 Pthyon 计算
  14. STL之容器——介绍
  15. 综述:如何研究植物基因组DNA羟甲基化(5hmC)?|易基因
  16. 模仿apple中国大陆官方
  17. SAP系统开发里程碑 2022 刘欣
  18. Pointer Networks简介及其应用
  19. 服务器抓不到mrcp信息,启动百度Mrcp服务器出错 错误码: 323
  20. 精益和敏捷的较量:你知道敏捷开发有 Scrum 和 Kanban 两种管理模式吗?

热门文章

  1. [Be a Coding Plasterer] Components 1:get Basic Things
  2. 如何分析解读systemstat dump产生的trc文件
  3. JavaScript 实现Map效果
  4. Golang通过syscall调用windows dll方法
  5. java static 变量,和方法从属于类
  6. 什么是Open-E?
  7. 《python可以这样学》第一章
  8. 227 用栈模拟汉诺塔问题
  9. 使用CocoaPods被卡住:Updating local specs repositories
  10. 数据结构之 二叉树---求二叉树后序遍历和层次遍历(先建树,再遍历)