【Python】urlopen小结

0X00   简介

urlopen是urllib的的一个方法,它属于类文件对象,具有文件对象的方法,如read()等,同时也具有自身的一些方法:

1、info()        返回响应包的头信息

2、info().getheader()    返回头信息中指定内容,如Content-Type值等

2、getcode()      返回响应码,如200表示可以访问,404表示无法访问

3、geturl          返回请求的url地址

0X01   作用

1、获取服务器返回的header内容

#coding:utf-8

import urllib

header=urllib.urlopen('http://www.baidu.com').info()

print header

print header.info().getheader('Content-Type')

2、获取服务器返回的body内容

#coding:utf-8

import urllib
import urllib2

url='http://127.0.0.1/sqli-labs-master/Less-15/'

req=urllib2.Request(url)  #创建请求对象

values={'uname':'admin','passwd':'admin'}  #请求的post数据

data=urllib.urlencode(values)  #对post数据进行url编码

resp=urllib2.urlopen(req,data).read()  #读取响应对象内容,将其赋值给resp

with open('data.txt','a') as fw:  
    for line in resp:
        fw.write(line)  #将resp内容写入data.txt

3、下载图片到本地

#coding:utf-8

import urllib

pic=urllib.urlopen('http://www.xdowns.com/image/logo.png').read()

with open('1.jpg','wb') as fw:    #以二进制格式写图片文件
    
    fw.write(pic)

 

 

 

posted @ 2018-04-03 11:00  Carrypan  阅读(1493)  评论(0编辑  收藏  举报