一、最基础的应用
import urllib2
url = r'http://www.baidu.com'
html = urllib2.urlopen(url).read()
print html
客户端与服务器端通过request与response来沟通,客户端先向服务端发送request,然后接收服务端返回的response
urllib2提供了request的类,可以让用户在发送请求前先构造一个request的对象,然后通过urllib2.urlopen方法来发送请求
import urllib2
url = r'http://www.baidu.com'
req = urllib2.Request(url)
html = urllib2.urlopen(req).read()
print html
上例中先使用
req = urllib2.Request(url)
实例化一个resquest对象,接下来使用
urllib2.urlopen(req)
来打开这个网页。
我们注意到在实例化Request对象的时候,队了url是必须的,还有几个默认的参数
基中data与header也是使用的比较多的,一些需要登录的才能浏览的网站经常需要这两个参数
import urllib
import urllib2
url = 'http://www.baidu.com/'
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()
print the_page
这个例子是向百度发送几个数据,这个例子是会返回一个错误页面,很正常,因为我们在访问百度的时候并不需要post什么信息,post了倒是会出错
百度是找不到相应的网页就会报错。
当然这个是POST数据,也可以用在GET方法,稍将上面的代码进行改造
百度是通过http://www.baidu.com/s?wd=XXX 来进行查询的,这样我们需要将{‘wd’:’xxx’}这个字典进行urlencode
#coding:utf-8
import urllib
import urllib2
url = 'http://www.baidu.com/s'
values = {'wd':'杨彦星'}
data = urllib.urlencode(values)
print data
url2 = url+'?'+data
response = urllib2.urlopen(url2)
the_page = response.read()
print the_page
以下以模拟登录人人网然后再显示首页内容为例来详细说明一下cookie的使用,以下是文档中给的例子,我们就通过改造这个例子来实现我们想要的功能
import cookielib, urllib2
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")
#coding:utf-8
import urllib2,urllib
import cookielib