经过urllib2抓取网页内容(1)

通过urllib2抓取网页内容(1)
一、urllib2发送请求
import urllib2
url = 'http://www.baidu.com'
req = urllib2.Request(url)
response = urllib2.urlopen(req)
print response.read()
print response.geturl()
print response.info()

urllib2用一个Request对象,来映射HTTP请求,并将这个请求传入urlopen()中去,返回response对象
Request =>Response  http就是基于这种请求/应答机制


   response对象,是一个文件对象,可以调用read(),info(),geturl()等方法
   response.read()  读取返回的内容
   response.info()获取返回header         
   response.geturl() 获取实际访问的url


urllib2使用相同的接口处理所有的URL头,比如可以这样创建一个ftp请求
req = urllib2.Request('ftp://duote.com')


二、POST请求


import urllib2
url = "http://www.duote.com/index?php"
data = {"softname":"quicktime.exe","size":"18763","md5":"HEN35FLK3WP"}
req = urllib2.Request(url,data)
response = urllib2.urlopen(req)
print response.read()


Request(url,data=None,headers={},orgin_req_host=None,univerifiable=False)

urlopen(url, data=None, timeout=<object object>, cafile=None, capath=None, cadefault=False, context=None)



三、GET请求


import urllib
import urllib2

url = "http://www.2345.com"
data = {'name':'Tom','age':'18','studynum':'002195'}

urlvalue = urllib.urlencode(data)
print urlvalue
r_url = url +'?' +urlvalue

data = urllib2.urlopen(r_url)

一般html表单,data需要编写成标准的形式,调用urllib.urlencode()进行urlencode编码,编写完然后用问号衔接 加到url后面

版权声明:本文为博主原创文章,未经博主允许不得转载。