使用Python的urllib2模块处理url和图片的技巧两则

yipeiwu_com7年前Python基础

获取带有中文参数的url内容
对于中文的参数如果不进行编码的话,python的urllib2直接处理会报错,我们可以先将中文转换成utf- 8编码,然后使用urllib2.quote方法对参数进行url编码后传递。

content = u'你好 sharejs.com'
content = content.encode('utf-8')
content = urllib2.quote(content)
api_url = 'http://www.sharejs.com/q=%s'%content
res = urllib2.urlopen(api_url)


获取远程图片的大小和尺寸
这段代码通过urllib2打开远程图片,通过cStringIO读取文件内容,不用保存到磁盘即可读取图片文件的信息

#!/usr/bin/env python
#encoding=utf-8

import cStringIO, urllib2, Image

url = '/zb_users/upload/202003/kpeeihczsj1.png'
file = urllib2.urlopen(url)
tmpIm = cStringIO.StringIO(file.read())
im = Image.open(tmpIm)

print im.format, im.size, im.mode

相关文章

通过Python 接口使用OpenCV的方法

一、在 Anaconda2 中配置 OpenCV 解压 opencv,添加系统环境变量,计算机-->右键属性-->高级系统设置-->环境变量-->系统变量--&g...

python shell根据ip获取主机名代码示例

这篇文章里我们主要分享了python中shell 根据 ip 获取 hostname 或根据 hostname 获取 ip的代码,具体介绍如下。 笔者有时候需要根据hostname获取i...

浅谈Pandas中map, applymap and apply的区别

1.apply() 当想让方程作用在一维的向量上时,可以使用apply来完成,如下所示 In [116]: frame = DataFrame(np.random.randn(4,...

Python lambda表达式filter、map、reduce函数用法解析

前言 lambda是表达式,用于创建匿名函数,可以和filter、map、reduce配合使用。 本文环境Python3.7。 一、lambda表达式 lambda 只包含一个语句,用...

Python最小二乘法矩阵

最小二乘法矩阵 #! /usr/bin/env python # -*- coding: utf-8 -*- import numpy as np def calc_left_k_m...