Python 2.7 获取网络信息(Urllib)
2017-06-30 14:09
323 查看
>>> import urllib
>>> google = urllib.urlopen('http://www.google.com')
>>> print 'http header:\n',google.info()
...............(一堆HTTP头信息)
>>> print 'http status:',google.getcode()
http status: 200
>>> print 'url:',google.geturl()
url:
http://www.google.com.hk/
>>>help(urllib.urlopen)
Help on function urlopen in module urllib:
urlopen(url, data=None, proxies=None)
Create a file-like object for the specified URL to read from.
参数 url 表示远程数据的路径,一般是 http 或者 ftp 路径。
参数 data 表示以 get 或者 post
方式提交到 url 的数据。
参数 proxies 表示用于代理的设置。
urlopen 返回一个类文件对象,它提供了如下方法:
read() , readline() , readlines(),fileno()和close(): 这些方法的使用与文件对象完全一样。
info():返回一个httplib.HTTPMessage 对象,表示远程服务器返回的头信息。
getcode():返回Http状态码,如果是http请求,200表示请求成功完成;404表示网址未找到。
geturl():返回请求的url地址。
下例 : 整个html抓取下来:
# 别惊讶,整个程序确实只用了两行代码
>>>import urllib
>>>print urllib.urlopen('http://www.google.com').read()
再熟悉一下:
google = urllib.urlopen('http://www.google.com')
print 'http header:/n', google.info()
print 'http status:', google.getcode()
print 'url:', google.geturl()
for line in google: # 就像在操作本地文件
print line,
google.close()
urlopen()
urllib 是 python 自带的一个抓取网页信息一个接口,他最主要的方法是 urlopen(),是基于
python 的 open() 方法的。下面是主要说明:
这里传入urlopen()的参数有特别说要求 : 要遵循一些网络协议,比如http,ftp,也就是说,在网址的开头必须要有
http://
这样的说明,如:urllib.urlopen('http://www.baidu.com')。
要么就是本地文件,本地文件需要使用file关键字,比如 urllib.urlopen('file:nowamagic.py'),注意,这里的hello.py是指的是当前的classpath所指定的内容,如果对hello.py这里有什么疑问那一定是python寻找classpath的顺序不是很清楚了,当然也可以直接写全部路径,urllib.urlopen('file:F:\pythontest\nowamagic.py')。
例如:
import urllib
f = urllib.urlopen('file:F:\pythontest\nowamagic.py')
a = f.read()
print a
urllib 的 代理设置:
import urllib
proxies = {'http':'http://***.***.***.***:1984'}
filehandle = urllib.urlopen('http://www.需要代理才能访问的网站.com/',proxies = proxies)
a = filehandle.read()
print a
以上是最基本代理,即代理访问到该网站,并且能够获得该网站的内容。但是如果遇到需要登录,或者需要cookie等的网站呢?
urlretrieve()
下面我们再来看看 urllib 模块提供的 urlretrieve() 函数。urlretrieve() 方法直接将远程数据下载到本地。
>>> help(urllib.urlretrieve)
Help on function urlretrieve in module urllib:
urlretrieve(url, filename=None, reporthook=None, data=None)
参数 finename 指定了保存本地路径(如果参数未指定,urllib会生成一个临时文件保存数据。)
参数 reporthook 是一个回调函数,当连接上服务器、以及相应的数据块传输完毕时会触发该回调, 我们可以利用这个回调函数来显示当前的下载进度。
参数 data 指 post 到服务器的数据,该方法返回一个包含两个元素的(filename, headers)元组,filename 表示保存到本地的路径,header 表示服务器的响应头。
下面通过例子来演示一下这个方法的使用,这个例子将 google 的 html 抓取到本地,保存在 D:/google.html 文件中,同时显示下载的进度。
import urllib
def cbk(a, b, c):
'''回调函数
@a: 已经下载的数据块
@b: 数据块的大小
@c: 远程文件的大小
'''
per = 100.0 * a * b / c
if per > 100:
per = 100
print '%.2f%%' % per
url = 'http://www.google.com'
local = 'd://google.html'
urllib.urlretrieve(url, local, cbk)
URL编码解码
url 中是不能出现一些特殊的符号的,有些符号有特殊的用途。比如以 get 方式提交数据的时候,会在 url 中添加 key=value 这样的字符串,所以在 value 中是不允许有 '=',因此要对其进行编码 ,比如 :
1.+ URL 中+号表示空格 %2B
2.空格 URL中的空格可以用+号或者编码 %20
3./ 分隔目录和子目录 %2F
4.? 分隔实际的 URL 和参数 %3F
5.% 指定特殊字符 %25
6.# 表示书签 %23
7.& URL 中指定的参数间的分隔符 %26
8.= URL 中指定参数的值 %3D
与此同时服务器接收到这些参数的时候,要进行解码,还原成原始的数据。这个时候,这些辅助方法会很有用:
urllib.quote(string[, safe]):对字符串进行编码。参数 safe 指定了不需要编码的字符;
urllib.unquote(string) :对字符串进行解码;
urllib.quote_plus(string [ , safe ] ) :与 urllib.quote 类似,但这个方法用'+'来替换' '(空格),而 quote 用'%20'来代替' '
urllib.unquote_plus(string ) :解码;
urllib.urlencode(query[, doseq]):将dict或者包含两个元素的元组列表转换成url参数。 例如 字典{'name': 'dark-bull', 'age': 200}将被转换为"name=dark-bull&age=200"
urllib.pathname2url(path):将本地路径转换成 url 路径;
urllib.url2pathname(path):将url路径转换成本地路径;
Python 2.7.5
>>> import urllib>>> data = 'name = ~nowamagic+5'>>> data1 = urllib.quote(data)>>> print data1name%20%3D%20%7Enowamagic%2B5>>> print urllib.unquote(data1)name =
~nowamagic+5>>> data2 = urllib.quote_plus(data)>>> print data2name+%3D+%7Enowamagic%2B5>>> print urllib.unquote_plus(data2)name = ~nowamagic+5>>> data3 = urllib.urlencode({ 'name': 'nowamagic-gonn', 'age': 200 })>>> print data3age=200&name=nowamagic-gonn>>>
data4 = urllib.pathname2url(r'd:/a/b/c/23.php')>>> print data4///D://a/b/c/23.php>>> print urllib.url2pathname(data4)D:\a\b\c\23.php
urllib 2
python 发展过程中,guido 越来越看不惯 urllib 的混乱结构了,但是很多人已经习惯 import urllib 了,并且用的还可以,所以 urllib 不管代码里多么混乱,但他能运行。很好,于是 guido
只能在urllib 外在开发了 urllib2,来满足一个有“洁癖”的程序员的心理需求。
import urllib2content = urllib2.urlopen('http://www.google.com/')c = content.read()print c
urlib2 是使用各种协议完成打开 url 的一个扩展包。最简单的使用方式是调用 urlopen() 方法,比如:
import urllib2content_stream = urllib2.urlopen('http://www.google.com/')content = content_stream.read()print content
即可以接受一个字符串型的 url 地址或者一个 Request 对象。将打开这个 url 并返回结果为一个像文件对象一样的对象。\
接下来是 OpenerDirector 操作类。这是一个管理很多处理类(Handler)的类。而所有这些 Handler 类都对应处理相应的协议,或者特殊功能。分别有下面的处理类:
BaseHandler
HTTPErrorProcessor
HTTPDefaultErrorHandler
HTTPRedirectHandler
ProxyHandler
AbstractBasicAuthHandler
HTTPBasicAuthHandler
ProxyBasicAuthHandler
AbstractDigestAuthHandler
ProxyDigestAuthHandler
AbstractHTTPHandler
HTTPHandler
HTTPCookieProcessor
UnknownHandler
FileHandler
FTPHandler
CacheFTPHandler
是不是很多?是不是和我说的结构简单不一致?不是的,他们都是遵循相应的规则,需求创建的类,甚至是相似的。你何必一口想吃成个胖子,全部都要会,先只管最最基本的需求吧,http 协议的处理类。
刚才我们说的最简单的 urlib2 的使用,也就是源码中给出的使用方式:
>>> google = urllib.urlopen('http://www.google.com')
>>> print 'http header:\n',google.info()
...............(一堆HTTP头信息)
>>> print 'http status:',google.getcode()
http status: 200
>>> print 'url:',google.geturl()
url:
http://www.google.com.hk/
>>>help(urllib.urlopen)
Help on function urlopen in module urllib:
urlopen(url, data=None, proxies=None)
Create a file-like object for the specified URL to read from.
参数 url 表示远程数据的路径,一般是 http 或者 ftp 路径。
参数 data 表示以 get 或者 post
方式提交到 url 的数据。
参数 proxies 表示用于代理的设置。
urlopen 返回一个类文件对象,它提供了如下方法:
read() , readline() , readlines(),fileno()和close(): 这些方法的使用与文件对象完全一样。
info():返回一个httplib.HTTPMessage 对象,表示远程服务器返回的头信息。
getcode():返回Http状态码,如果是http请求,200表示请求成功完成;404表示网址未找到。
geturl():返回请求的url地址。
下例 : 整个html抓取下来:
# 别惊讶,整个程序确实只用了两行代码
>>>import urllib
>>>print urllib.urlopen('http://www.google.com').read()
再熟悉一下:
google = urllib.urlopen('http://www.google.com')
print 'http header:/n', google.info()
print 'http status:', google.getcode()
print 'url:', google.geturl()
for line in google: # 就像在操作本地文件
print line,
google.close()
urlopen()
urllib 是 python 自带的一个抓取网页信息一个接口,他最主要的方法是 urlopen(),是基于
python 的 open() 方法的。下面是主要说明:
这里传入urlopen()的参数有特别说要求 : 要遵循一些网络协议,比如http,ftp,也就是说,在网址的开头必须要有
http://
这样的说明,如:urllib.urlopen('http://www.baidu.com')。
要么就是本地文件,本地文件需要使用file关键字,比如 urllib.urlopen('file:nowamagic.py'),注意,这里的hello.py是指的是当前的classpath所指定的内容,如果对hello.py这里有什么疑问那一定是python寻找classpath的顺序不是很清楚了,当然也可以直接写全部路径,urllib.urlopen('file:F:\pythontest\nowamagic.py')。
例如:
import urllib
f = urllib.urlopen('file:F:\pythontest\nowamagic.py')
a = f.read()
print a
urllib 的 代理设置:
import urllib
proxies = {'http':'http://***.***.***.***:1984'}
filehandle = urllib.urlopen('http://www.需要代理才能访问的网站.com/',proxies = proxies)
a = filehandle.read()
print a
以上是最基本代理,即代理访问到该网站,并且能够获得该网站的内容。但是如果遇到需要登录,或者需要cookie等的网站呢?
urlretrieve()
下面我们再来看看 urllib 模块提供的 urlretrieve() 函数。urlretrieve() 方法直接将远程数据下载到本地。
>>> help(urllib.urlretrieve)
Help on function urlretrieve in module urllib:
urlretrieve(url, filename=None, reporthook=None, data=None)
参数 finename 指定了保存本地路径(如果参数未指定,urllib会生成一个临时文件保存数据。)
参数 reporthook 是一个回调函数,当连接上服务器、以及相应的数据块传输完毕时会触发该回调, 我们可以利用这个回调函数来显示当前的下载进度。
参数 data 指 post 到服务器的数据,该方法返回一个包含两个元素的(filename, headers)元组,filename 表示保存到本地的路径,header 表示服务器的响应头。
下面通过例子来演示一下这个方法的使用,这个例子将 google 的 html 抓取到本地,保存在 D:/google.html 文件中,同时显示下载的进度。
import urllib
def cbk(a, b, c):
'''回调函数
@a: 已经下载的数据块
@b: 数据块的大小
@c: 远程文件的大小
'''
per = 100.0 * a * b / c
if per > 100:
per = 100
print '%.2f%%' % per
url = 'http://www.google.com'
local = 'd://google.html'
urllib.urlretrieve(url, local, cbk)
URL编码解码
url 中是不能出现一些特殊的符号的,有些符号有特殊的用途。比如以 get 方式提交数据的时候,会在 url 中添加 key=value 这样的字符串,所以在 value 中是不允许有 '=',因此要对其进行编码 ,比如 :
1.+ URL 中+号表示空格 %2B
2.空格 URL中的空格可以用+号或者编码 %20
3./ 分隔目录和子目录 %2F
4.? 分隔实际的 URL 和参数 %3F
5.% 指定特殊字符 %25
6.# 表示书签 %23
7.& URL 中指定的参数间的分隔符 %26
8.= URL 中指定参数的值 %3D
与此同时服务器接收到这些参数的时候,要进行解码,还原成原始的数据。这个时候,这些辅助方法会很有用:
urllib.quote(string[, safe]):对字符串进行编码。参数 safe 指定了不需要编码的字符;
urllib.unquote(string) :对字符串进行解码;
urllib.quote_plus(string [ , safe ] ) :与 urllib.quote 类似,但这个方法用'+'来替换' '(空格),而 quote 用'%20'来代替' '
urllib.unquote_plus(string ) :解码;
urllib.urlencode(query[, doseq]):将dict或者包含两个元素的元组列表转换成url参数。 例如 字典{'name': 'dark-bull', 'age': 200}将被转换为"name=dark-bull&age=200"
urllib.pathname2url(path):将本地路径转换成 url 路径;
urllib.url2pathname(path):将url路径转换成本地路径;
Python 2.7.5
>>> import urllib>>> data = 'name = ~nowamagic+5'>>> data1 = urllib.quote(data)>>> print data1name%20%3D%20%7Enowamagic%2B5>>> print urllib.unquote(data1)name =
~nowamagic+5>>> data2 = urllib.quote_plus(data)>>> print data2name+%3D+%7Enowamagic%2B5>>> print urllib.unquote_plus(data2)name = ~nowamagic+5>>> data3 = urllib.urlencode({ 'name': 'nowamagic-gonn', 'age': 200 })>>> print data3age=200&name=nowamagic-gonn>>>
data4 = urllib.pathname2url(r'd:/a/b/c/23.php')>>> print data4///D://a/b/c/23.php>>> print urllib.url2pathname(data4)D:\a\b\c\23.php
urllib 2
python 发展过程中,guido 越来越看不惯 urllib 的混乱结构了,但是很多人已经习惯 import urllib 了,并且用的还可以,所以 urllib 不管代码里多么混乱,但他能运行。很好,于是 guido
只能在urllib 外在开发了 urllib2,来满足一个有“洁癖”的程序员的心理需求。
import urllib2content = urllib2.urlopen('http://www.google.com/')c = content.read()print c
urlib2 是使用各种协议完成打开 url 的一个扩展包。最简单的使用方式是调用 urlopen() 方法,比如:
import urllib2content_stream = urllib2.urlopen('http://www.google.com/')content = content_stream.read()print content
即可以接受一个字符串型的 url 地址或者一个 Request 对象。将打开这个 url 并返回结果为一个像文件对象一样的对象。\
接下来是 OpenerDirector 操作类。这是一个管理很多处理类(Handler)的类。而所有这些 Handler 类都对应处理相应的协议,或者特殊功能。分别有下面的处理类:
BaseHandler
HTTPErrorProcessor
HTTPDefaultErrorHandler
HTTPRedirectHandler
ProxyHandler
AbstractBasicAuthHandler
HTTPBasicAuthHandler
ProxyBasicAuthHandler
AbstractDigestAuthHandler
ProxyDigestAuthHandler
AbstractHTTPHandler
HTTPHandler
HTTPCookieProcessor
UnknownHandler
FileHandler
FTPHandler
CacheFTPHandler
是不是很多?是不是和我说的结构简单不一致?不是的,他们都是遵循相应的规则,需求创建的类,甚至是相似的。你何必一口想吃成个胖子,全部都要会,先只管最最基本的需求吧,http 协议的处理类。
刚才我们说的最简单的 urlib2 的使用,也就是源码中给出的使用方式:
相关文章推荐
- linux系统下 python获取 内存、cpu、负载、网络流量、硬盘等信息
- python urllib* 获取网页信息
- Python3 urllib(网络数据获取 模块)
- python实例31[urllib.request.urlopen获取股票信息]
- Python 网络爬虫与信息获取(一)—— requests 库的网络爬虫
- python之psutil模块(获取系统性能信息(CPU,内存,磁盘,网络)
- 使用python获取系统网络信息
- 转载:linux系统下 python获取 内存、cpu、负载、网络流量、硬盘等信息
- Python——urllib函数网络文件获取
- Python网络编程小例子:使用python获取网站域名信息
- Python实现可获取网易页面所有文本信息的网易网络爬虫功能示例
- Python网络编程 获取页面中的天气信息
- python获取网络文件信息
- python 标准库获取网络信息
- Python3 urllib(网络数据获取 模块)
- python自动化运维学习------使用模块psutil获取系统cpu、内存、磁盘、网络、进程等信息
- Python3 urllib(网络数据获取 模块)
- [python&php 网络编程]获取远程机器的信息
- python获取网络文件信息藏
- linux系统下 python获取 内存、cpu、负载、网络流量、硬盘等信息